installed pty
authorVSORC <josuer08@gmail.com>
Thu, 14 Nov 2019 20:10:32 +0000 (16:10 -0400)
committerVSORC <josuer08@gmail.com>
Thu, 14 Nov 2019 20:10:32 +0000 (16:10 -0400)
295 files changed:
1  2 
node_modules/node-pty/LICENSE
node_modules/node-pty/README.md
node_modules/node-pty/binding.gyp
node_modules/node-pty/build/Makefile
node_modules/node-pty/build/Release/pty.node
node_modules/node-pty/build/binding.Makefile
node_modules/node-pty/build/config.gypi
node_modules/node-pty/build/pty.target.mk
node_modules/node-pty/deps/.editorconfig
node_modules/node-pty/deps/winpty/.drone.yml
node_modules/node-pty/deps/winpty/.gitattributes
node_modules/node-pty/deps/winpty/.gitignore
node_modules/node-pty/deps/winpty/LICENSE
node_modules/node-pty/deps/winpty/Makefile
node_modules/node-pty/deps/winpty/README.md
node_modules/node-pty/deps/winpty/RELEASES.md
node_modules/node-pty/deps/winpty/VERSION.txt
node_modules/node-pty/deps/winpty/configure
node_modules/node-pty/deps/winpty/misc/.gitignore
node_modules/node-pty/deps/winpty/misc/BufferResizeTests.cc
node_modules/node-pty/deps/winpty/misc/ChangeScreenBuffer.cc
node_modules/node-pty/deps/winpty/misc/ClearConsole.cc
node_modules/node-pty/deps/winpty/misc/ConinMode.cc
node_modules/node-pty/deps/winpty/misc/ConinMode.ps1
node_modules/node-pty/deps/winpty/misc/ConoutMode.cc
node_modules/node-pty/deps/winpty/misc/DebugClient.py
node_modules/node-pty/deps/winpty/misc/DebugServer.py
node_modules/node-pty/deps/winpty/misc/DumpLines.py
node_modules/node-pty/deps/winpty/misc/EnableExtendedFlags.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Consolas.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Lucida.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP932.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP936.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP949.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP950.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/MinimumWindowWidths.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Results.txt
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Windows10SetFontBugginess.txt
node_modules/node-pty/deps/winpty/misc/FontSurvey.cc
node_modules/node-pty/deps/winpty/misc/FormatChar.h
node_modules/node-pty/deps/winpty/misc/FreezePerfTest.cc
node_modules/node-pty/deps/winpty/misc/GetCh.cc
node_modules/node-pty/deps/winpty/misc/GetConsolePos.cc
node_modules/node-pty/deps/winpty/misc/GetFont.cc
node_modules/node-pty/deps/winpty/misc/IdentifyConsoleWindow.ps1
node_modules/node-pty/deps/winpty/misc/IsNewConsole.cc
node_modules/node-pty/deps/winpty/misc/MouseInputNotes.txt
node_modules/node-pty/deps/winpty/misc/MoveConsoleWindow.cc
node_modules/node-pty/deps/winpty/misc/Notes.txt
node_modules/node-pty/deps/winpty/misc/OSVersion.cc
node_modules/node-pty/deps/winpty/misc/ScreenBufferFreezeInactive.cc
node_modules/node-pty/deps/winpty/misc/ScreenBufferTest.cc
node_modules/node-pty/deps/winpty/misc/ScreenBufferTest2.cc
node_modules/node-pty/deps/winpty/misc/SelectAllTest.cc
node_modules/node-pty/deps/winpty/misc/SetBufferSize.cc
node_modules/node-pty/deps/winpty/misc/SetCursorPos.cc
node_modules/node-pty/deps/winpty/misc/SetFont.cc
node_modules/node-pty/deps/winpty/misc/SetWindowRect.cc
node_modules/node-pty/deps/winpty/misc/ShowArgv.cc
node_modules/node-pty/deps/winpty/misc/ShowConsoleInput.cc
node_modules/node-pty/deps/winpty/misc/Spew.py
node_modules/node-pty/deps/winpty/misc/TestUtil.cc
node_modules/node-pty/deps/winpty/misc/UnicodeDoubleWidthTest.cc
node_modules/node-pty/deps/winpty/misc/UnicodeWideTest1.cc
node_modules/node-pty/deps/winpty/misc/UnicodeWideTest2.cc
node_modules/node-pty/deps/winpty/misc/UnixEcho.cc
node_modules/node-pty/deps/winpty/misc/Utf16Echo.cc
node_modules/node-pty/deps/winpty/misc/VeryLargeRead.cc
node_modules/node-pty/deps/winpty/misc/VkEscapeTest.cc
node_modules/node-pty/deps/winpty/misc/Win10ResizeWhileFrozen.cc
node_modules/node-pty/deps/winpty/misc/Win10WrapTest1.cc
node_modules/node-pty/deps/winpty/misc/Win10WrapTest2.cc
node_modules/node-pty/deps/winpty/misc/Win32Echo1.cc
node_modules/node-pty/deps/winpty/misc/Win32Echo2.cc
node_modules/node-pty/deps/winpty/misc/Win32Test1.cc
node_modules/node-pty/deps/winpty/misc/Win32Test2.cc
node_modules/node-pty/deps/winpty/misc/Win32Test3.cc
node_modules/node-pty/deps/winpty/misc/Win32Write1.cc
node_modules/node-pty/deps/winpty/misc/WindowsBugCrashReader.cc
node_modules/node-pty/deps/winpty/misc/WriteConsole.cc
node_modules/node-pty/deps/winpty/misc/build32.sh
node_modules/node-pty/deps/winpty/misc/build64.sh
node_modules/node-pty/deps/winpty/misc/color-test.sh
node_modules/node-pty/deps/winpty/misc/font-notes.txt
node_modules/node-pty/deps/winpty/misc/winbug-15048.cc
node_modules/node-pty/deps/winpty/ship/build-pty4j-libpty.bat
node_modules/node-pty/deps/winpty/ship/common_ship.py
node_modules/node-pty/deps/winpty/ship/make_msvc_package.py
node_modules/node-pty/deps/winpty/ship/ship.py
node_modules/node-pty/deps/winpty/src/agent/Agent.cc
node_modules/node-pty/deps/winpty/src/agent/Agent.h
node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.cc
node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.h
node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.cc
node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.h
node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.cc
node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.h
node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.cc
node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.h
node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.cc
node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.h
node_modules/node-pty/deps/winpty/src/agent/Coord.h
node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.cc
node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.h
node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.cc
node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.h
node_modules/node-pty/deps/winpty/src/agent/DsrSender.h
node_modules/node-pty/deps/winpty/src/agent/EventLoop.cc
node_modules/node-pty/deps/winpty/src/agent/EventLoop.h
node_modules/node-pty/deps/winpty/src/agent/InputMap.cc
node_modules/node-pty/deps/winpty/src/agent/InputMap.h
node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.cc
node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.h
node_modules/node-pty/deps/winpty/src/agent/NamedPipe.cc
node_modules/node-pty/deps/winpty/src/agent/NamedPipe.h
node_modules/node-pty/deps/winpty/src/agent/Scraper.cc
node_modules/node-pty/deps/winpty/src/agent/Scraper.h
node_modules/node-pty/deps/winpty/src/agent/SimplePool.h
node_modules/node-pty/deps/winpty/src/agent/SmallRect.h
node_modules/node-pty/deps/winpty/src/agent/Terminal.cc
node_modules/node-pty/deps/winpty/src/agent/Terminal.h
node_modules/node-pty/deps/winpty/src/agent/UnicodeEncoding.h
node_modules/node-pty/deps/winpty/src/agent/UnicodeEncodingTest.cc
node_modules/node-pty/deps/winpty/src/agent/Win32Console.cc
node_modules/node-pty/deps/winpty/src/agent/Win32Console.h
node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.cc
node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.h
node_modules/node-pty/deps/winpty/src/agent/main.cc
node_modules/node-pty/deps/winpty/src/agent/subdir.mk
node_modules/node-pty/deps/winpty/src/configurations.gypi
node_modules/node-pty/deps/winpty/src/debugserver/DebugServer.cc
node_modules/node-pty/deps/winpty/src/debugserver/subdir.mk
node_modules/node-pty/deps/winpty/src/include/winpty.h
node_modules/node-pty/deps/winpty/src/include/winpty_constants.h
node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.cc
node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.h
node_modules/node-pty/deps/winpty/src/libwinpty/LibWinptyException.h
node_modules/node-pty/deps/winpty/src/libwinpty/WinptyInternal.h
node_modules/node-pty/deps/winpty/src/libwinpty/subdir.mk
node_modules/node-pty/deps/winpty/src/libwinpty/winpty.cc
node_modules/node-pty/deps/winpty/src/shared/AgentMsg.h
node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.cc
node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.h
node_modules/node-pty/deps/winpty/src/shared/Buffer.cc
node_modules/node-pty/deps/winpty/src/shared/Buffer.h
node_modules/node-pty/deps/winpty/src/shared/DebugClient.cc
node_modules/node-pty/deps/winpty/src/shared/DebugClient.h
node_modules/node-pty/deps/winpty/src/shared/GenRandom.cc
node_modules/node-pty/deps/winpty/src/shared/GenRandom.h
node_modules/node-pty/deps/winpty/src/shared/GetCommitHash.bat
node_modules/node-pty/deps/winpty/src/shared/Mutex.h
node_modules/node-pty/deps/winpty/src/shared/OsModule.h
node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.cc
node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.h
node_modules/node-pty/deps/winpty/src/shared/PrecompiledHeader.h
node_modules/node-pty/deps/winpty/src/shared/StringBuilder.h
node_modules/node-pty/deps/winpty/src/shared/StringBuilderTest.cc
node_modules/node-pty/deps/winpty/src/shared/StringUtil.cc
node_modules/node-pty/deps/winpty/src/shared/StringUtil.h
node_modules/node-pty/deps/winpty/src/shared/TimeMeasurement.h
node_modules/node-pty/deps/winpty/src/shared/UnixCtrlChars.h
node_modules/node-pty/deps/winpty/src/shared/UpdateGenVersion.bat
node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.cc
node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.h
node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.cc
node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.h
node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.cc
node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.h
node_modules/node-pty/deps/winpty/src/shared/WinptyException.cc
node_modules/node-pty/deps/winpty/src/shared/WinptyException.h
node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.cc
node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.h
node_modules/node-pty/deps/winpty/src/shared/winpty_snprintf.h
node_modules/node-pty/deps/winpty/src/subdir.mk
node_modules/node-pty/deps/winpty/src/tests/subdir.mk
node_modules/node-pty/deps/winpty/src/tests/trivial_test.cc
node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.cc
node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.h
node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.cc
node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.h
node_modules/node-pty/deps/winpty/src/unix-adapter/Util.cc
node_modules/node-pty/deps/winpty/src/unix-adapter/Util.h
node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.cc
node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.h
node_modules/node-pty/deps/winpty/src/unix-adapter/main.cc
node_modules/node-pty/deps/winpty/src/unix-adapter/subdir.mk
node_modules/node-pty/deps/winpty/src/winpty.gyp
node_modules/node-pty/deps/winpty/vcbuild.bat
node_modules/node-pty/lib/conpty_console_list_agent.js
node_modules/node-pty/lib/conpty_console_list_agent.js.map
node_modules/node-pty/lib/eventEmitter2.js
node_modules/node-pty/lib/eventEmitter2.js.map
node_modules/node-pty/lib/eventEmitter2.test.js
node_modules/node-pty/lib/eventEmitter2.test.js.map
node_modules/node-pty/lib/index.js
node_modules/node-pty/lib/index.js.map
node_modules/node-pty/lib/interfaces.js
node_modules/node-pty/lib/interfaces.js.map
node_modules/node-pty/lib/terminal.js
node_modules/node-pty/lib/terminal.js.map
node_modules/node-pty/lib/terminal.test.js
node_modules/node-pty/lib/terminal.test.js.map
node_modules/node-pty/lib/testUtils.test.js
node_modules/node-pty/lib/testUtils.test.js.map
node_modules/node-pty/lib/types.js
node_modules/node-pty/lib/types.js.map
node_modules/node-pty/lib/unixTerminal.js
node_modules/node-pty/lib/unixTerminal.js.map
node_modules/node-pty/lib/unixTerminal.test.js
node_modules/node-pty/lib/unixTerminal.test.js.map
node_modules/node-pty/lib/utils.js
node_modules/node-pty/lib/utils.js.map
node_modules/node-pty/lib/windowsPtyAgent.js
node_modules/node-pty/lib/windowsPtyAgent.js.map
node_modules/node-pty/lib/windowsPtyAgent.test.js
node_modules/node-pty/lib/windowsPtyAgent.test.js.map
node_modules/node-pty/lib/windowsTerminal.js
node_modules/node-pty/lib/windowsTerminal.js.map
node_modules/node-pty/lib/windowsTerminal.test.js
node_modules/node-pty/lib/windowsTerminal.test.js.map
node_modules/node-pty/node_modules/nan/CHANGELOG.md
node_modules/node-pty/node_modules/nan/LICENSE.md
node_modules/node-pty/node_modules/nan/README.md
node_modules/node-pty/node_modules/nan/doc/asyncworker.md
node_modules/node-pty/node_modules/nan/doc/buffers.md
node_modules/node-pty/node_modules/nan/doc/callback.md
node_modules/node-pty/node_modules/nan/doc/converters.md
node_modules/node-pty/node_modules/nan/doc/errors.md
node_modules/node-pty/node_modules/nan/doc/json.md
node_modules/node-pty/node_modules/nan/doc/maybe_types.md
node_modules/node-pty/node_modules/nan/doc/methods.md
node_modules/node-pty/node_modules/nan/doc/new.md
node_modules/node-pty/node_modules/nan/doc/node_misc.md
node_modules/node-pty/node_modules/nan/doc/object_wrappers.md
node_modules/node-pty/node_modules/nan/doc/persistent.md
node_modules/node-pty/node_modules/nan/doc/scopes.md
node_modules/node-pty/node_modules/nan/doc/script.md
node_modules/node-pty/node_modules/nan/doc/string_bytes.md
node_modules/node-pty/node_modules/nan/doc/v8_internals.md
node_modules/node-pty/node_modules/nan/doc/v8_misc.md
node_modules/node-pty/node_modules/nan/include_dirs.js
node_modules/node-pty/node_modules/nan/nan.h
node_modules/node-pty/node_modules/nan/nan_callbacks.h
node_modules/node-pty/node_modules/nan/nan_callbacks_12_inl.h
node_modules/node-pty/node_modules/nan/nan_callbacks_pre_12_inl.h
node_modules/node-pty/node_modules/nan/nan_converters.h
node_modules/node-pty/node_modules/nan/nan_converters_43_inl.h
node_modules/node-pty/node_modules/nan/nan_converters_pre_43_inl.h
node_modules/node-pty/node_modules/nan/nan_define_own_property_helper.h
node_modules/node-pty/node_modules/nan/nan_implementation_12_inl.h
node_modules/node-pty/node_modules/nan/nan_implementation_pre_12_inl.h
node_modules/node-pty/node_modules/nan/nan_json.h
node_modules/node-pty/node_modules/nan/nan_maybe_43_inl.h
node_modules/node-pty/node_modules/nan/nan_maybe_pre_43_inl.h
node_modules/node-pty/node_modules/nan/nan_new.h
node_modules/node-pty/node_modules/nan/nan_object_wrap.h
node_modules/node-pty/node_modules/nan/nan_persistent_12_inl.h
node_modules/node-pty/node_modules/nan/nan_persistent_pre_12_inl.h
node_modules/node-pty/node_modules/nan/nan_private.h
node_modules/node-pty/node_modules/nan/nan_string_bytes.h
node_modules/node-pty/node_modules/nan/nan_typedarray_contents.h
node_modules/node-pty/node_modules/nan/nan_weak.h
node_modules/node-pty/node_modules/nan/package.json
node_modules/node-pty/node_modules/nan/tools/1to2.js
node_modules/node-pty/node_modules/nan/tools/README.md
node_modules/node-pty/node_modules/nan/tools/package.json
node_modules/node-pty/package.json
node_modules/node-pty/scripts/install.js
node_modules/node-pty/scripts/post-install.js
node_modules/node-pty/scripts/publish.js
node_modules/node-pty/src/conpty_console_list_agent.ts
node_modules/node-pty/src/eventEmitter2.test.ts
node_modules/node-pty/src/eventEmitter2.ts
node_modules/node-pty/src/index.ts
node_modules/node-pty/src/interfaces.ts
node_modules/node-pty/src/native.d.ts
node_modules/node-pty/src/terminal.test.ts
node_modules/node-pty/src/terminal.ts
node_modules/node-pty/src/testUtils.test.ts
node_modules/node-pty/src/types.ts
node_modules/node-pty/src/unix/pty.cc
node_modules/node-pty/src/unixTerminal.test.ts
node_modules/node-pty/src/unixTerminal.ts
node_modules/node-pty/src/utils.ts
node_modules/node-pty/src/win/conpty.cc
node_modules/node-pty/src/win/conpty_console_list.cc
node_modules/node-pty/src/win/path_util.cc
node_modules/node-pty/src/win/path_util.h
node_modules/node-pty/src/win/winpty.cc
node_modules/node-pty/src/windowsPtyAgent.test.ts
node_modules/node-pty/src/windowsPtyAgent.ts
node_modules/node-pty/src/windowsTerminal.test.ts
node_modules/node-pty/src/windowsTerminal.ts
node_modules/node-pty/typings/node-pty.d.ts
src/views/starter.ejs

index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..22f780daf969a6af3ad94bad02c57c5790e5c4f6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,69 @@@
++Copyright (c) 2012-2015, Christopher Jeffrey (https://github.com/chjj/)
++
++Permission is hereby granted, free of charge, to any person obtaining a copy
++of this software and associated documentation files (the "Software"), to deal
++in the Software without restriction, including without limitation the rights
++to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
++copies of the Software, and to permit persons to whom the Software is
++furnished to do so, subject to the following conditions:
++
++The above copyright notice and this permission notice shall be included in
++all copies or substantial portions of the Software.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
++OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
++THE SOFTWARE.
++
++
++
++The MIT License (MIT)
++
++Copyright (c) 2016, Daniel Imms (http://www.growingwiththeweb.com)
++
++Permission is hereby granted, free of charge, to any person obtaining a copy
++of this software and associated documentation files (the "Software"), to deal
++in the Software without restriction, including without limitation the rights
++to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
++copies of the Software, and to permit persons to whom the Software is
++furnished to do so, subject to the following conditions:
++
++The above copyright notice and this permission notice shall be included in all
++copies or substantial portions of the Software.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
++OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++SOFTWARE.
++
++
++
++MIT License
++
++Copyright (c) 2018 - present Microsoft Corporation
++
++All rights reserved.
++
++Permission is hereby granted, free of charge, to any person obtaining a copy
++of this software and associated documentation files (the "Software"), to deal
++in the Software without restriction, including without limitation the rights
++to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
++copies of the Software, and to permit persons to whom the Software is
++furnished to do so, subject to the following conditions:
++
++The above copyright notice and this permission notice shall be included in all
++copies or substantial portions of the Software.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
++OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++SOFTWARE.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a36bba38d46829f9edf1de6ad2d23984626d7f10
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,146 @@@
++# node-pty
++
++[![Build Status](https://dev.azure.com/vscode/node-pty/_apis/build/status/Microsoft.node-pty)](https://dev.azure.com/vscode/node-pty/_build/latest?definitionId=11)
++
++`forkpty(3)` bindings for node.js. This allows you to fork processes with pseudoterminal file descriptors. It returns a terminal object which allows reads and writes.
++
++This is useful for:
++
++- Writing a terminal emulator (eg. via [xterm.js](https://github.com/sourcelair/xterm.js)).
++- Getting certain programs to *think* you're a terminal, such as when you need a program to send you control sequences.
++
++`node-pty` supports Linux, macOS and Windows. Windows support is possible by utilizing the [Windows conpty API](https://blogs.msdn.microsoft.com/commandline/2018/08/02/windows-command-line-introducing-the-windows-pseudo-console-conpty/) on Windows 1809+ and the [winpty](https://github.com/rprichard/winpty) library in older version.
++
++## Real-world Uses
++
++`node-pty` powers many different terminal emulators, including:
++
++- [Microsoft Visual Studio Code](https://code.visualstudio.com)
++- [Hyper](https://hyper.is/)
++- [Upterm](https://github.com/railsware/upterm)
++- [Script Runner](https://github.com/ioquatix/script-runner) for Atom.
++- [Theia](https://github.com/theia-ide/theia)
++- [FreeMAN](https://github.com/matthew-matvei/freeman) file manager
++- [atom-xterm](https://atom.io/packages/atom-xterm) - Atom plugin for providing terminals inside your Atom workspace.
++- [Termination](https://atom.io/packages/termination) - Another Atom plugin that provides terminals inside your Atom workspace.
++- [electerm](https://github.com/electerm/electerm) Terminal/ssh/sftp client(linux, mac, win).
++- [Extraterm](http://extraterm.org/)
++- [Wetty](https://github.com/krishnasrinivas/wetty) Browser based Terminal over HTTP and HTTPS
++
++Do you use node-pty in your application as well? Please open a [Pull Request](https://github.com/Tyriar/node-pty/pulls) to include it here. We would love to have it in our list.
++
++## Example Usage
++
++```js
++var os = require('os');
++var pty = require('node-pty');
++
++var shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
++
++var ptyProcess = pty.spawn(shell, [], {
++  name: 'xterm-color',
++  cols: 80,
++  rows: 30,
++  cwd: process.env.HOME,
++  env: process.env
++});
++
++ptyProcess.on('data', function(data) {
++  process.stdout.write(data);
++});
++
++ptyProcess.write('ls\r');
++ptyProcess.resize(100, 40);
++ptyProcess.write('ls\r');
++```
++
++## Building
++
++```bash
++# Install dependencies and build C++
++npm install
++# Compile TypeScript -> JavaScript
++npm run tsc
++```
++
++## Dependencies
++
++### Linux/Ubuntu
++
++```
++sudo apt install -y make python build-essential
++```
++
++The following are also needed:
++
++- Node.JS 10+
++
++### Windows
++
++`npm install` requires some tools to be present in the system like Python and C++ compiler. Windows users can easily install them by running the following command in PowerShell as administrator. For more information see https://github.com/felixrieseberg/windows-build-tools:
++
++```sh
++npm install --global --production windows-build-tools
++```
++
++The following are also needed:
++
++- [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk) - only the "Desktop C++ Apps" components are needed to be installed
++- Node.JS 10+
++
++## Debugging
++
++[The wiki](https://github.com/Microsoft/node-pty/wiki/Debugging) contains instructions for debugging node-pty.
++
++## Security
++
++All processes launched from node-pty will launch at the same permission level of the parent process. Take care particularly when using node-pty inside a server that's accessible on the internet. We recommend launching the pty inside a container to protect your host machine.
++
++## Thread Safety
++
++Note that node-pty is not thread safe so running it across multiple worker threads in node.js could cause issues.
++
++## Flow Control
++
++Automatic flow control can be enabled by either providing `handleFlowControl = true` in the constructor options or setting it later on:
++
++```js
++const PAUSE = '\x13';   // XOFF
++const RESUME = '\x11';  // XON
++
++const ptyProcess = pty.spawn(shell, [], {handleFlowControl: true});
++
++// flow control in action
++ptyProcess.write(PAUSE);  // pty will block and pause the slave program
++...
++ptyProcess.write(RESUME); // pty will enter flow mode and resume the slave program
++
++// temporarily disable/re-enable flow control
++ptyProcess.handleFlowControl = false;
++...
++ptyProcess.handleFlowControl = true;
++```
++
++By default `PAUSE` and `RESUME` are XON/XOFF control codes (as shown above). To avoid conflicts in environments that use these control codes for different purposes the messages can be customized as `flowControlPause: string` and `flowControlResume: string` in the constructor options. `PAUSE` and `RESUME` are not passed to the underlying pseudoterminal if flow control is enabled.
++
++## Troubleshooting
++
++### Powershell gives error 8009001d
++
++> Internal Windows PowerShell error.  Loading managed Windows PowerShell failed with error 8009001d.
++
++This happens when PowerShell is launched with no `SystemRoot` environment variable present.
++
++### ConnectNamedPipe failed: Windows error 232
++
++This error can occur due to anti-virus software intercepting winpty from creating a pty. To workaround this you can exclude this file from your anti-virus scanning `node-pty\build\Release\winpty-agent.exe`
++
++## pty.js
++
++This project is forked from [chjj/pty.js](https://github.com/chjj/pty.js) with the primary goals being to provide better support for later Node.JS versions and Windows.
++
++## License
++
++Copyright (c) 2012-2015, Christopher Jeffrey (MIT License).<br>
++Copyright (c) 2016, Daniel Imms (MIT License).<br>
++Copyright (c) 2018, Microsoft Corporation (MIT License).
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..dac085f95632fbd3c661166eb2520359b517d81c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,85 @@@
++{
++  'conditions': [
++    ['OS=="win"', {
++      'targets': [
++        {
++          'target_name': 'conpty',
++          'include_dirs' : [
++            '<!(node -e "require(\'nan\')")'
++          ],
++          'sources' : [
++            'src/win/conpty.cc',
++            'src/win/path_util.cc'
++          ],
++          'libraries': [
++            'shlwapi.lib'
++          ]
++        },
++        {
++          'target_name': 'conpty_console_list',
++          'include_dirs' : [
++            '<!(node -e "require(\'nan\')")'
++          ],
++          'sources' : [
++            'src/win/conpty_console_list.cc'
++          ]
++        },
++        {
++          'target_name': 'pty',
++          'include_dirs' : [
++            '<!(node -e "require(\'nan\')")',
++            'deps/winpty/src/include',
++          ],
++          # Disabled due to winpty
++          'msvs_disabled_warnings': [ 4506, 4530 ],
++          'dependencies' : [
++            'deps/winpty/src/winpty.gyp:winpty-agent',
++            'deps/winpty/src/winpty.gyp:winpty',
++          ],
++          'sources' : [
++            'src/win/winpty.cc',
++            'src/win/path_util.cc'
++          ],
++          'libraries': [
++            'shlwapi.lib'
++          ],
++        }
++      ]
++    }, { # OS!="win"
++      'targets': [{
++        'target_name': 'pty',
++        'include_dirs' : [
++          '<!(node -e "require(\'nan\')")'
++        ],
++        'sources': [
++          'src/unix/pty.cc'
++        ],
++        'libraries': [
++          '-lutil'
++        ],
++        'conditions': [
++          # http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html
++          #   One some systems (at least including Cygwin, Interix,
++          #   OSF/1 4 and 5, and Mac OS X) linking with -lutil is not required.
++          ['OS=="mac" or OS=="solaris"', {
++            'libraries!': [
++              '-lutil'
++            ]
++          }],
++          ['OS=="mac"', {
++            "xcode_settings": {
++              "OTHER_CPLUSPLUSFLAGS": [
++                "-std=c++11",
++                "-stdlib=libc++"
++              ],
++              "OTHER_LDFLAGS": [
++                "-stdlib=libc++"
++              ],
++              "MACOSX_DEPLOYMENT_TARGET":"10.7"
++            }
++          }]
++        ]
++      }]
++    }]
++  ]
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8bea2538117a93b80b559974b896c50b8b7a7907
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,324 @@@
++# We borrow heavily from the kernel build setup, though we are simpler since
++# we don't have Kconfig tweaking settings on us.
++
++# The implicit make rules have it looking for RCS files, among other things.
++# We instead explicitly write all the rules we care about.
++# It's even quicker (saves ~200ms) to pass -r on the command line.
++MAKEFLAGS=-r
++
++# The source directory tree.
++srcdir := ..
++abs_srcdir := $(abspath $(srcdir))
++
++# The name of the builddir.
++builddir_name ?= .
++
++# The V=1 flag on command line makes us verbosely print command lines.
++ifdef V
++  quiet=
++else
++  quiet=quiet_
++endif
++
++# Specify BUILDTYPE=Release on the command line for a release build.
++BUILDTYPE ?= Release
++
++# Directory all our build output goes into.
++# Note that this must be two directories beneath src/ for unit tests to pass,
++# as they reach into the src/ directory for data with relative paths.
++builddir ?= $(builddir_name)/$(BUILDTYPE)
++abs_builddir := $(abspath $(builddir))
++depsdir := $(builddir)/.deps
++
++# Object output directory.
++obj := $(builddir)/obj
++abs_obj := $(abspath $(obj))
++
++# We build up a list of every single one of the targets so we can slurp in the
++# generated dependency rule Makefiles in one pass.
++all_deps :=
++
++
++
++CC.target ?= $(CC)
++CFLAGS.target ?= $(CFLAGS)
++CXX.target ?= $(CXX)
++CXXFLAGS.target ?= $(CXXFLAGS) $(CPPFLAGS)
++LINK.target ?= $(LINK)
++LDFLAGS.target ?= $(LDFLAGS)
++AR.target ?= $(AR)
++
++# C++ apps need to be linked with g++.
++LINK ?= $(CXX.target)
++
++# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
++# to replicate this environment fallback in make as well.
++CC.host ?= gcc
++CFLAGS.host ?=
++CXX.host ?= g++
++CXXFLAGS.host ?=
++LINK.host ?= $(CXX.host)
++LDFLAGS.host ?=
++AR.host ?= ar
++
++# Define a dir function that can handle spaces.
++# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
++# "leading spaces cannot appear in the text of the first argument as written.
++# These characters can be put into the argument value by variable substitution."
++empty :=
++space := $(empty) $(empty)
++
++# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
++replace_spaces = $(subst $(space),?,$1)
++unreplace_spaces = $(subst ?,$(space),$1)
++dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
++
++# Flags to make gcc output dependency info.  Note that you need to be
++# careful here to use the flags that ccache and distcc can understand.
++# We write to a dep file on the side first and then rename at the end
++# so we can't end up with a broken dep file.
++depfile = $(depsdir)/$(call replace_spaces,$@).d
++DEPFLAGS = -MMD -MF $(depfile).raw
++
++# We have to fixup the deps output in a few ways.
++# (1) the file output should mention the proper .o file.
++# ccache or distcc lose the path to the target, so we convert a rule of
++# the form:
++#   foobar.o: DEP1 DEP2
++# into
++#   path/to/foobar.o: DEP1 DEP2
++# (2) we want missing files not to cause us to fail to build.
++# We want to rewrite
++#   foobar.o: DEP1 DEP2 \
++#               DEP3
++# to
++#   DEP1:
++#   DEP2:
++#   DEP3:
++# so if the files are missing, they're just considered phony rules.
++# We have to do some pretty insane escaping to get those backslashes
++# and dollar signs past make, the shell, and sed at the same time.
++# Doesn't work with spaces, but that's fine: .d files have spaces in
++# their names replaced with other characters.
++define fixup_dep
++# The depfile may not exist if the input file didn't have any #includes.
++touch $(depfile).raw
++# Fixup path as in (1).
++sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
++# Add extra rules as in (2).
++# We remove slashes and replace spaces with new lines;
++# remove blank lines;
++# delete the first line and append a colon to the remaining lines.
++sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
++  grep -v '^$$'                             |\
++  sed -e 1d -e 's|$$|:|'                     \
++    >> $(depfile)
++rm $(depfile).raw
++endef
++
++# Command definitions:
++# - cmd_foo is the actual command to run;
++# - quiet_cmd_foo is the brief-output summary of the command.
++
++quiet_cmd_cc = CC($(TOOLSET)) $@
++cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
++
++quiet_cmd_cxx = CXX($(TOOLSET)) $@
++cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
++
++quiet_cmd_touch = TOUCH $@
++cmd_touch = touch $@
++
++quiet_cmd_copy = COPY $@
++# send stderr to /dev/null to ignore messages when linking directories.
++cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
++
++quiet_cmd_alink = AR($(TOOLSET)) $@
++cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
++
++quiet_cmd_alink_thin = AR($(TOOLSET)) $@
++cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
++
++# Due to circular dependencies between libraries :(, we wrap the
++# special "figure out circular dependencies" flags around the entire
++# input list during linking.
++quiet_cmd_link = LINK($(TOOLSET)) $@
++cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
++
++# We support two kinds of shared objects (.so):
++# 1) shared_library, which is just bundling together many dependent libraries
++# into a link line.
++# 2) loadable_module, which is generating a module intended for dlopen().
++#
++# They differ only slightly:
++# In the former case, we want to package all dependent code into the .so.
++# In the latter case, we want to package just the API exposed by the
++# outermost module.
++# This means shared_library uses --whole-archive, while loadable_module doesn't.
++# (Note that --whole-archive is incompatible with the --start-group used in
++# normal linking.)
++
++# Other shared-object link notes:
++# - Set SONAME to the library filename so our binaries don't reference
++# the local, absolute paths used on the link command-line.
++quiet_cmd_solink = SOLINK($(TOOLSET)) $@
++cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
++
++quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
++cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
++
++
++# Define an escape_quotes function to escape single quotes.
++# This allows us to handle quotes properly as long as we always use
++# use single quotes and escape_quotes.
++escape_quotes = $(subst ','\'',$(1))
++# This comment is here just to include a ' to unconfuse syntax highlighting.
++# Define an escape_vars function to escape '$' variable syntax.
++# This allows us to read/write command lines with shell variables (e.g.
++# $LD_LIBRARY_PATH), without triggering make substitution.
++escape_vars = $(subst $$,$$$$,$(1))
++# Helper that expands to a shell command to echo a string exactly as it is in
++# make. This uses printf instead of echo because printf's behaviour with respect
++# to escape sequences is more portable than echo's across different shells
++# (e.g., dash, bash).
++exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
++
++# Helper to compare the command we're about to run against the command
++# we logged the last time we ran the command.  Produces an empty
++# string (false) when the commands match.
++# Tricky point: Make has no string-equality test function.
++# The kernel uses the following, but it seems like it would have false
++# positives, where one string reordered its arguments.
++#   arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
++#                       $(filter-out $(cmd_$@), $(cmd_$(1))))
++# We instead substitute each for the empty string into the other, and
++# say they're equal if both substitutions produce the empty string.
++# .d files contain ? instead of spaces, take that into account.
++command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
++                       $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
++
++# Helper that is non-empty when a prerequisite changes.
++# Normally make does this implicitly, but we force rules to always run
++# so we can check their command lines.
++#   $? -- new prerequisites
++#   $| -- order-only dependencies
++prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
++
++# Helper that executes all postbuilds until one fails.
++define do_postbuilds
++  @E=0;\
++  for p in $(POSTBUILDS); do\
++    eval $$p;\
++    E=$$?;\
++    if [ $$E -ne 0 ]; then\
++      break;\
++    fi;\
++  done;\
++  if [ $$E -ne 0 ]; then\
++    rm -rf "$@";\
++    exit $$E;\
++  fi
++endef
++
++# do_cmd: run a command via the above cmd_foo names, if necessary.
++# Should always run for a given target to handle command-line changes.
++# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
++# Third argument, if non-zero, makes it do POSTBUILDS processing.
++# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
++# spaces already and dirx strips the ? characters.
++define do_cmd
++$(if $(or $(command_changed),$(prereq_changed)),
++  @$(call exact_echo,  $($(quiet)cmd_$(1)))
++  @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
++  $(if $(findstring flock,$(word 1,$(cmd_$1))),
++    @$(cmd_$(1))
++    @echo "  $(quiet_cmd_$(1)): Finished",
++    @$(cmd_$(1))
++  )
++  @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
++  @$(if $(2),$(fixup_dep))
++  $(if $(and $(3), $(POSTBUILDS)),
++    $(call do_postbuilds)
++  )
++)
++endef
++
++# Declare the "all" target first so it is the default,
++# even though we don't have the deps yet.
++.PHONY: all
++all:
++
++# make looks for ways to re-generate included makefiles, but in our case, we
++# don't have a direct way. Explicitly telling make that it has nothing to do
++# for them makes it go faster.
++%.d: ;
++
++# Use FORCE_DO_CMD to force a target to run.  Should be coupled with
++# do_cmd.
++.PHONY: FORCE_DO_CMD
++FORCE_DO_CMD:
++
++TOOLSET := target
++# Suffix rules, putting all outputs into $(obj).
++$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++
++# Try building from generated source, too.
++$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++
++$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
++      @$(call do_cmd,cc,1)
++
++
++ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
++    $(findstring $(join ^,$(prefix)),\
++                 $(join ^,pty.target.mk)))),)
++  include pty.target.mk
++endif
++
++quiet_cmd_regen_makefile = ACTION Regenerating $@
++cmd_regen_makefile = cd $(srcdir); /usr/share/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/pi/VSoRC/node_modules/node-pty/build/config.gypi -I/usr/share/node-gyp/addon.gypi -I/usr/include/nodejs/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/usr/include/nodejs" "-Dnode_gyp_dir=/usr/share/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/home/pi/VSoRC/node_modules/node-pty" binding.gyp
++Makefile: $(srcdir)/../../../../../usr/include/nodejs/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../usr/share/node-gyp/addon.gypi
++      $(call do_cmd,regen_makefile)
++
++# "all" is a concatenation of the "all" targets from all the included
++# sub-makefiles. This is just here to clarify.
++all:
++
++# Add in dependency-tracking rules.  $(all_deps) is the list of every single
++# target in our tree. Only consider the ones with .d (dependency) info:
++d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
++ifneq ($(d_files),)
++  include $(d_files)
++endif
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9dd15cfe07ad4066a0f3e2bc53d3d7daa03d90e7
new file mode 100755 (executable)
Binary files differ
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..059b76f4134f1636b6a37cda5422231ee2626180
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,6 @@@
++# This file is generated by gyp; do not edit.
++
++export builddir_name ?= ./build/.
++.PHONY: all
++all:
++      $(MAKE) pty
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cf372b9a61e939b442c6d0428602243e9b30a55b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,151 @@@
++# Do not edit. File was generated by node-gyp's "configure" step
++{
++  "target_defaults": {
++    "cflags": [],
++    "default_configuration": "Release",
++    "defines": [],
++    "include_dirs": [],
++    "libraries": []
++  },
++  "variables": {
++    "arm_float_abi": "hard",
++    "arm_fpu": "vfp",
++    "arm_thumb": 0,
++    "arm_version": "6",
++    "asan": 0,
++    "coverage": "false",
++    "debug_devtools": "node",
++    "debug_http2": "false",
++    "debug_nghttp2": "false",
++    "force_dynamic_crt": 0,
++    "host_arch": "arm",
++    "icu_gyp_path": "tools/icu/icu-system.gyp",
++    "icu_small": "false",
++    "llvm_version": 0,
++    "node_byteorder": "little",
++    "node_enable_d8": "false",
++    "node_enable_v8_vtunejit": "false",
++    "node_install_npm": "false",
++    "node_module_version": 57,
++    "node_no_browser_globals": "false",
++    "node_prefix": "/usr",
++    "node_release_urlbase": "",
++    "node_shared": "false",
++    "node_shared_cares": "true",
++    "node_shared_http_parser": "true",
++    "node_shared_libuv": "true",
++    "node_shared_nghttp2": "false",
++    "node_shared_openssl": "true",
++    "node_shared_zlib": "true",
++    "node_tag": "",
++    "node_use_bundled_v8": "true",
++    "node_use_dtrace": "false",
++    "node_use_etw": "false",
++    "node_use_lttng": "false",
++    "node_use_openssl": "true",
++    "node_use_perfctr": "false",
++    "node_use_v8_platform": "true",
++    "node_without_node_options": "false",
++    "openssl_fips": "",
++    "openssl_no_asm": 0,
++    "shlib_suffix": "so.57",
++    "target_arch": "arm",
++    "uv_parent_path": "/deps/uv/",
++    "uv_use_dtrace": "false",
++    "v8_enable_gdbjit": 0,
++    "v8_enable_i18n_support": 1,
++    "v8_enable_inspector": 1,
++    "v8_no_strict_aliasing": 1,
++    "v8_optimized_debug": 0,
++    "v8_promise_internal_field_count": 1,
++    "v8_random_seed": 0,
++    "v8_trace_maps": 0,
++    "v8_use_snapshot": "false",
++    "want_separate_host_toolset": 0,
++    "nodedir": "/usr/include/nodejs",
++    "copy_dev_lib": "true",
++    "standalone_static_library": 1,
++    "cache_lock_stale": "60000",
++    "sign_git_tag": "",
++    "user_agent": "npm/1.4.21 node/v8.11.1 linux arm",
++    "always_auth": "",
++    "bin_links": "true",
++    "key": "",
++    "description": "true",
++    "fetch_retries": "2",
++    "heading": "npm",
++    "user": "",
++    "force": "",
++    "cache_min": "10",
++    "init_license": "ISC",
++    "editor": "vi",
++    "rollback": "true",
++    "cache_max": "Infinity",
++    "userconfig": "/home/pi/.npmrc",
++    "engine_strict": "",
++    "init_author_name": "",
++    "init_author_url": "",
++    "tmp": "/tmp",
++    "depth": "Infinity",
++    "save_dev": "",
++    "usage": "",
++    "https_proxy": "",
++    "onload_script": "",
++    "rebuild_bundle": "true",
++    "save_bundle": "",
++    "shell": "/bin/bash",
++    "prefix": "/usr/local",
++    "registry": "https://registry.npmjs.org/",
++    "__DO_NOT_MODIFY_THIS_FILE___use__etc_npmrc_instead_": "true",
++    "browser": "",
++    "cache_lock_wait": "10000",
++    "save_optional": "",
++    "searchopts": "",
++    "versions": "",
++    "cache": "/home/pi/.npm",
++    "ignore_scripts": "",
++    "searchsort": "name",
++    "version": "",
++    "local_address": "",
++    "viewer": "man",
++    "color": "true",
++    "fetch_retry_mintimeout": "10000",
++    "umask": "18",
++    "fetch_retry_maxtimeout": "60000",
++    "message": "%s",
++    "ca": "",
++    "cert": "",
++    "global": "",
++    "link": "",
++    "save": "",
++    "unicode": "true",
++    "long": "",
++    "production": "",
++    "unsafe_perm": "true",
++    "node_version": "8.11.1",
++    "tag": "latest",
++    "git_tag_version": "true",
++    "shrinkwrap": "true",
++    "fetch_retry_factor": "10",
++    "npat": "",
++    "proprietary_attribs": "true",
++    "save_exact": "",
++    "strict_ssl": "true",
++    "username": "",
++    "globalconfig": "/etc/npmrc",
++    "dev": "",
++    "init_module": "/home/pi/.npm-init.js",
++    "parseable": "",
++    "globalignorefile": "/etc/npmignore",
++    "cache_lock_retries": "10",
++    "save_prefix": "^",
++    "group": "1000",
++    "init_author_email": "",
++    "searchexclude": "",
++    "git": "git",
++    "optional": "true",
++    "email": "",
++    "json": "",
++    "spin": "true"
++  }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..528472fd2eae6c5ba4402fdde709aedeb00d275f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,140 @@@
++# This file is generated by gyp; do not edit.
++
++TOOLSET := target
++TARGET := pty
++DEFS_Debug := \
++      '-DNODE_GYP_MODULE_NAME=pty' \
++      '-DUSING_UV_SHARED=1' \
++      '-DUSING_V8_SHARED=1' \
++      '-DV8_DEPRECATION_WARNINGS=1' \
++      '-D_LARGEFILE_SOURCE' \
++      '-D_FILE_OFFSET_BITS=64' \
++      '-DBUILDING_NODE_EXTENSION' \
++      '-DDEBUG' \
++      '-D_DEBUG' \
++      '-DV8_ENABLE_CHECKS'
++
++# Flags passed to all source files.
++CFLAGS_Debug := \
++      -fPIC \
++      -pthread \
++      -Wall \
++      -Wextra \
++      -Wno-unused-parameter \
++      -g \
++      -O0
++
++# Flags passed to only C files.
++CFLAGS_C_Debug :=
++
++# Flags passed to only C++ files.
++CFLAGS_CC_Debug := \
++      -fno-rtti \
++      -fno-exceptions \
++      -std=gnu++0x
++
++INCS_Debug := \
++      -I/usr/include/nodejs/include/node \
++      -I/usr/include/nodejs/src \
++      -I/usr/include/nodejs/deps/uv/include \
++      -I/usr/include/nodejs/deps/v8/include \
++      -I$(srcdir)/node_modules/nan
++
++DEFS_Release := \
++      '-DNODE_GYP_MODULE_NAME=pty' \
++      '-DUSING_UV_SHARED=1' \
++      '-DUSING_V8_SHARED=1' \
++      '-DV8_DEPRECATION_WARNINGS=1' \
++      '-D_LARGEFILE_SOURCE' \
++      '-D_FILE_OFFSET_BITS=64' \
++      '-DBUILDING_NODE_EXTENSION'
++
++# Flags passed to all source files.
++CFLAGS_Release := \
++      -fPIC \
++      -pthread \
++      -Wall \
++      -Wextra \
++      -Wno-unused-parameter \
++      -O3 \
++      -fno-omit-frame-pointer
++
++# Flags passed to only C files.
++CFLAGS_C_Release :=
++
++# Flags passed to only C++ files.
++CFLAGS_CC_Release := \
++      -fno-rtti \
++      -fno-exceptions \
++      -std=gnu++0x
++
++INCS_Release := \
++      -I/usr/include/nodejs/include/node \
++      -I/usr/include/nodejs/src \
++      -I/usr/include/nodejs/deps/uv/include \
++      -I/usr/include/nodejs/deps/v8/include \
++      -I$(srcdir)/node_modules/nan
++
++OBJS := \
++      $(obj).target/$(TARGET)/src/unix/pty.o
++
++# Add to the list of files we specially track dependencies for.
++all_deps += $(OBJS)
++
++# CFLAGS et al overrides must be target-local.
++# See "Target-specific Variable Values" in the GNU Make manual.
++$(OBJS): TOOLSET := $(TOOLSET)
++$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE))  $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
++$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE))  $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
++
++# Suffix rules, putting all outputs into $(obj).
++
++$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++
++# Try building from generated source, too.
++
++$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++
++$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
++      @$(call do_cmd,cxx,1)
++
++# End of this set of suffix rules
++### Rules for final target.
++LDFLAGS_Debug := \
++      -pthread \
++      -rdynamic
++
++LDFLAGS_Release := \
++      -pthread \
++      -rdynamic
++
++LIBS := \
++      -lutil
++
++$(obj).target/pty.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
++$(obj).target/pty.node: LIBS := $(LIBS)
++$(obj).target/pty.node: TOOLSET := $(TOOLSET)
++$(obj).target/pty.node: $(OBJS) FORCE_DO_CMD
++      $(call do_cmd,solink_module)
++
++all_deps += $(obj).target/pty.node
++# Add target alias
++.PHONY: pty
++pty: $(builddir)/pty.node
++
++# Copy this to the executable output path.
++$(builddir)/pty.node: TOOLSET := $(TOOLSET)
++$(builddir)/pty.node: $(obj).target/pty.node FORCE_DO_CMD
++      $(call do_cmd,copy)
++
++all_deps += $(builddir)/pty.node
++# Short alias for building this executable.
++.PHONY: pty.node
++pty.node: $(obj).target/pty.node $(builddir)/pty.node
++
++# Add executable to "all" target.
++.PHONY: all
++all: $(builddir)/pty.node
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8a39199985cc18f25ee3a68955d8edadc9bb527d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,2 @@@
++# Have editor config ignore this directory
++root = true
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..63d853f624a953ac18396a657e50d75b5731b930
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,17 @@@
++# Build configure for https://www.tea-ci.org (fork of Drone CI with Msys2 support)
++build:
++  image: teaci/msys$$arch
++  pull: true
++  shell: msys$$arch
++  commands:
++    - pacman -S --needed --noconfirm --noprogressbar mingw-w64-cross-gcc mingw-w64-cross-crt-git
++    - ./configure
++    - make
++    - make tests
++    - build/trivial_test.exe
++    - mintty --log - --exec build/winpty.exe cmd /c ver | grep Windows
++
++matrix:
++  arch:
++    - 64
++    - 32
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..36d4c60f1a7811b18cdbe751c29cf599151b0bc8
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,19 @@@
++*               text=auto
++*.bat           text eol=crlf
++*.c             text
++*.cc            text
++*.gyp           text
++*.gypi          text
++*.h             text
++*.ps1           text eol=crlf
++*.rst           text
++*.sh            text
++*.txt           text
++.gitignore      text
++.gitattributes  text
++Makefile        text
++configure       text
++
++*.sh            eol=lf
++configure       eol=lf
++VERSION.txt     eol=lf
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..89e60bdbaec68f1f5d1bb3635ce51b1562a0f494
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,15 @@@
++*.sln
++*.suo
++*.vcxproj
++*.vcxproj.filters
++*.pyc
++winpty.sdf
++winpty.opensdf
++/config.mk
++/build
++/build-gyp
++/build-libpty
++/ship/packages
++/src/Default
++/src/Release
++/src/gen
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..246fbe01135727bcb06d31c29b966b4301de21ed
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,21 @@@
++The MIT License (MIT)
++
++Copyright (c) 2011-2016 Ryan Prichard
++
++Permission is hereby granted, free of charge, to any person obtaining a copy
++of this software and associated documentation files (the "Software"), to
++deal in the Software without restriction, including without limitation the
++rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++sell copies of the Software, and to permit persons to whom the Software is
++furnished to do so, subject to the following conditions:
++
++The above copyright notice and this permission notice shall be included in
++all copies or substantial portions of the Software.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++IN THE SOFTWARE.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8b3d0ae1f01ce4aa3cb2ef5970f641622d2333ec
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,166 @@@
++# Copyright (c) 2011-2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++# Use make -n to see the actual command-lines make would run.
++
++# The default "make install" prefix is /usr/local.  Pass PREFIX=<path> on the
++# command-line to override the default.
++
++.SECONDEXPANSION :
++
++.PHONY : default
++default : all
++
++PREFIX := /usr/local
++UNIX_ADAPTER_EXE := winpty.exe
++MINGW_ENABLE_CXX11_FLAG := -std=c++11
++USE_PCH := 1
++
++COMMON_CXXFLAGS :=
++UNIX_CXXFLAGS :=
++MINGW_CXXFLAGS :=
++MINGW_LDFLAGS :=
++UNIX_LDFLAGS :=
++
++# Include config.mk but complain if it hasn't been created yet.
++ifeq "$(wildcard config.mk)" ""
++    $(error config.mk does not exist.  Please run ./configure)
++endif
++include config.mk
++
++COMMON_CXXFLAGS += \
++      -MMD -Wall \
++      -DUNICODE \
++      -D_UNICODE \
++      -D_WIN32_WINNT=0x0501 \
++      -Ibuild/gen
++
++UNIX_CXXFLAGS += \
++      $(COMMON_CXXFLAGS)
++
++MINGW_CXXFLAGS += \
++      $(COMMON_CXXFLAGS) \
++      -O2 \
++      $(MINGW_ENABLE_CXX11_FLAG)
++
++MINGW_LDFLAGS += -static -static-libgcc -static-libstdc++
++UNIX_LDFLAGS += $(UNIX_LDFLAGS_STATIC)
++
++ifeq "$(USE_PCH)" "1"
++MINGW_CXXFLAGS += -include build/mingw/PrecompiledHeader.h
++PCH_DEP := build/mingw/PrecompiledHeader.h.gch
++else
++PCH_DEP :=
++endif
++
++build/gen/GenVersion.h : VERSION.txt $(COMMIT_HASH_DEP) | $$(@D)/.mkdir
++      $(info Updating build/gen/GenVersion.h)
++      @echo "const char GenVersion_Version[] = \"$(shell cat VERSION.txt | tr -d '\r\n')\";" > build/gen/GenVersion.h
++      @echo "const char GenVersion_Commit[] = \"$(COMMIT_HASH)\";" >> build/gen/GenVersion.h
++
++build/mingw/PrecompiledHeader.h : src/shared/PrecompiledHeader.h | $$(@D)/.mkdir
++      $(info Copying $< to $@)
++      @cp $< $@
++
++build/mingw/PrecompiledHeader.h.gch : build/mingw/PrecompiledHeader.h | $$(@D)/.mkdir
++      $(info Compiling $<)
++      @$(MINGW_CXX) $(MINGW_CXXFLAGS) -c -o $@ $<
++
++-include build/mingw/PrecompiledHeader.h.d
++
++define def_unix_target
++build/$1/%.o : src/%.cc | $$$$(@D)/.mkdir
++      $$(info Compiling $$<)
++      @$$(UNIX_CXX) $$(UNIX_CXXFLAGS) $2 -I src/include -c -o $$@ $$<
++endef
++
++define def_mingw_target
++build/$1/%.o : src/%.cc $$(PCH_DEP) | $$$$(@D)/.mkdir
++      $$(info Compiling $$<)
++      @$$(MINGW_CXX) $$(MINGW_CXXFLAGS) $2 -I src/include -c -o $$@ $$<
++endef
++
++include src/subdir.mk
++
++.PHONY : all
++all : $(ALL_TARGETS)
++
++.PHONY : tests
++tests : $(TEST_PROGRAMS)
++
++.PHONY : install-bin
++install-bin : all
++      mkdir -p $(PREFIX)/bin
++      install -m 755 -p -s build/$(UNIX_ADAPTER_EXE) $(PREFIX)/bin
++      install -m 755 -p -s build/winpty.dll $(PREFIX)/bin
++      install -m 755 -p -s build/winpty-agent.exe $(PREFIX)/bin
++
++.PHONY : install-debugserver
++install-debugserver : all
++      mkdir -p $(PREFIX)/bin
++      install -m 755 -p -s build/winpty-debugserver.exe $(PREFIX)/bin
++
++.PHONY : install-lib
++install-lib : all
++      mkdir -p $(PREFIX)/lib
++      install -m 644 -p build/winpty.lib $(PREFIX)/lib
++
++.PHONY : install-doc
++install-doc :
++      mkdir -p $(PREFIX)/share/doc/winpty
++      install -m 644 -p LICENSE $(PREFIX)/share/doc/winpty
++      install -m 644 -p README.md $(PREFIX)/share/doc/winpty
++      install -m 644 -p RELEASES.md $(PREFIX)/share/doc/winpty
++
++.PHONY : install-include
++install-include :
++      mkdir -p $(PREFIX)/include/winpty
++      install -m 644 -p src/include/winpty.h $(PREFIX)/include/winpty
++      install -m 644 -p src/include/winpty_constants.h $(PREFIX)/include/winpty
++
++.PHONY : install
++install : \
++      install-bin \
++      install-debugserver \
++      install-lib \
++      install-doc \
++      install-include
++
++.PHONY : clean
++clean :
++      rm -fr build
++
++.PHONY : clean-msvc
++clean-msvc :
++      rm -fr src/Default src/Release src/.vs src/gen
++      rm -f src/*.vcxproj src/*.vcxproj.filters src/*.sln src/*.sdf
++
++.PHONY : distclean
++distclean : clean
++      rm -f config.mk
++
++.PRECIOUS : %.mkdir
++%.mkdir :
++      $(info Creating directory $(dir $@))
++      @mkdir -p $(dir $@)
++      @touch $@
++
++src/%.h :
++      @echo "Missing header file $@ (stale dependency file?)"
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a6520fc3531048c016fd3c664528d1eed83ddc47
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,151 @@@
++# winpty
++
++[![Build Status](https://tea-ci.org/api/badges/rprichard/winpty/status.svg)](https://tea-ci.org/rprichard/winpty)
++
++winpty is a Windows software package providing an interface similar to a Unix
++pty-master for communicating with Windows console programs.  The package
++consists of a library (libwinpty) and a tool for Cygwin and MSYS for running
++Windows console programs in a Cygwin/MSYS pty.
++
++The software works by starting the `winpty-agent.exe` process with a new,
++hidden console window, which bridges between the console API and terminal
++input/output escape codes.  It polls the hidden console's screen buffer for
++changes and generates a corresponding stream of output.
++
++The Unix adapter allows running Windows console programs (e.g. CMD, PowerShell,
++IronPython, etc.) under `mintty` or Cygwin's `sshd` with
++properly-functioning input (e.g. arrow and function keys) and output (e.g. line
++buffering).  The library could be also useful for writing a non-Cygwin SSH
++server.
++
++## Supported Windows versions
++
++winpty runs on Windows XP through Windows 10, including server versions.  It
++can be compiled into either 32-bit or 64-bit binaries.
++
++## Cygwin/MSYS adapter (`winpty.exe`)
++
++### Prerequisites
++
++You need the following to build winpty:
++
++* A Cygwin or MSYS installation
++* GNU make
++* A MinGW g++ toolchain capable of compiling C++11 code to build `winpty.dll`
++  and `winpty-agent.exe`
++* A g++ toolchain targeting Cygwin or MSYS to build `winpty.exe`
++
++Winpty requires two g++ toolchains as it is split into two parts. The
++`winpty.dll` and `winpty-agent.exe` binaries interface with the native
++Windows command prompt window so they are compiled with the native MinGW
++toolchain.  The `winpty.exe` binary interfaces with the MSYS/Cygwin terminal so
++it is compiled with the MSYS/Cygwin toolchain.
++
++MinGW appears to be split into two distributions -- MinGW (creates 32-bit
++binaries) and MinGW-w64 (creates both 32-bit and 64-bit binaries).  Either
++one is generally acceptable.
++
++#### Cygwin packages
++
++The default g++ compiler for Cygwin targets Cygwin itself, but Cygwin also
++packages MinGW-w64 compilers.  As of this writing, the necessary packages are:
++
++* Either `mingw64-i686-gcc-g++` or `mingw64-x86_64-gcc-g++`.  Select the
++  appropriate compiler for your CPU architecture.
++* `gcc-g++`
++* `make`
++
++As of this writing (2016-01-23), only the MinGW-w64 compiler is acceptable.
++The MinGW compiler (e.g. from the `mingw-gcc-g++` package) is no longer
++maintained and is too buggy.
++
++#### MSYS packages
++
++For the original MSYS, use the `mingw-get` tool (MinGW Installation Manager),
++and select at least these components:
++
++* `mingw-developer-toolkit`
++* `mingw32-base`
++* `mingw32-gcc-g++`
++* `msys-base`
++* `msys-system-builder`
++
++When running `./configure`, make sure that `mingw32-g++` is in your
++`PATH`.  It will be in the `C:\MinGW\bin` directory.
++
++#### MSYS2 packages
++
++For MSYS2, use `pacman` and install at least these packages:
++
++* `msys/gcc`
++* `mingw32/mingw-w64-i686-gcc` or `mingw64/mingw-w64-x86_64-gcc`.  Select
++  the appropriate compiler for your CPU architecture.
++* `make`
++
++MSYS2 provides three start menu shortcuts for starting MSYS2:
++
++* MinGW-w64 Win32 Shell
++* MinGW-w64 Win64 Shell
++* MSYS2 Shell
++
++To build winpty, use the MinGW-w64 {Win32,Win64} shortcut of the architecture
++matching MSYS2.  These shortcuts will put the g++ compiler from the
++`{mingw32,mingw64}/mingw-w64-{i686,x86_64}-gcc` packages into the `PATH`.
++
++Alternatively, instead of installing `mingw32/mingw-w64-i686-gcc` or
++`mingw64/mingw-w64-x86_64-gcc`, install the `mingw-w64-cross-gcc` and
++`mingw-w64-cross-crt-git` packages.  These packages install cross-compilers
++into `/opt/bin`, and then any of the three shortcuts will work.
++
++### Building the Unix adapter
++
++In the project directory, run `./configure`, then `make`, then `make install`.
++By default, winpty is installed into `/usr/local`.  Pass `PREFIX=<path>` to
++`make install` to override this default.
++
++### Using the Unix adapter
++
++To run a Windows console program in `mintty` or Cygwin `sshd`, prepend
++`winpty` to the command-line:
++
++    $ winpty powershell
++    Windows PowerShell
++    Copyright (C) 2009 Microsoft Corporation. All rights reserved.
++
++    PS C:\rprichard\proj\winpty> 10 + 20
++    30
++    PS C:\rprichard\proj\winpty> exit
++
++## Embedding winpty / MSVC compilation
++
++See `src/include/winpty.h` for the prototypes of functions exported by
++`winpty.dll`.
++
++Only the `winpty.exe` binary uses Cygwin; all the other binaries work without
++it and can be compiled with either MinGW or MSVC.  To compile using MSVC,
++download gyp and run `gyp -I configurations.gypi` in the `src` subdirectory.
++This will generate a `winpty.sln` and associated project files.  See the
++`src/winpty.gyp` and `src/configurations.gypi` files for notes on dealing with
++MSVC versions and different architectures.
++
++Compiling winpty with MSVC currently requires MSVC 2013 or newer.
++
++## Debugging winpty
++
++winpty comes with a tool for collecting timestamped debugging output.  To use
++it:
++
++1. Run `winpty-debugserver.exe` on the same computer as winpty.
++2. Set the `WINPTY_DEBUG` environment variable to `trace` for the
++   `winpty.exe` process and/or the process using `libwinpty.dll`.
++
++winpty also recognizes a `WINPTY_SHOW_CONSOLE` environment variable.  Set it
++to 1 to prevent winpty from hiding the console window.
++
++## Copyright
++
++This project is distributed under the MIT license (see the `LICENSE` file in
++the project root).
++
++By submitting a pull request for this project, you agree to license your
++contribution under the MIT license to this project.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..768cdf90e369ae5e570f90441184c2a358c62aa8
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,280 @@@
++# Next Version
++
++Input handling changes:
++
++ * Improve Ctrl-C handling with programs that use unprocessed input. (e.g.
++   Ctrl-C now cancels input with PowerShell on Windows 10.)
++   [#116](https://github.com/rprichard/winpty/issues/116)
++ * Fix a theoretical issue with input event ordering.
++   [#117](https://github.com/rprichard/winpty/issues/117)
++ * Ctrl/Shift+{Arrow,Home,End} keys now work with IntelliJ.
++   [#118](https://github.com/rprichard/winpty/issues/118)
++
++# Version 0.4.3 (2017-05-17)
++
++Input handling changes:
++
++ * winpty sets `ENHANCED_KEY` for arrow and navigation keys.  This fixes an
++   issue with the Ruby REPL.
++   [#99](https://github.com/rprichard/winpty/issues/99)
++ * AltGr keys are handled better now.
++   [#109](https://github.com/rprichard/winpty/issues/109)
++ * In `ENABLE_VIRTUAL_TERMINAL_INPUT` mode, when typing Home/End with a
++   modifier (e.g. Ctrl), winpty now generates an H/F escape sequence like
++   `^[[1;5F` rather than a 1/4 escape like `^[[4;5~`.
++   [#114](https://github.com/rprichard/winpty/issues/114)
++
++Resizing and scraping fixes:
++
++ * winpty now synthesizes a `WINDOW_BUFFER_SIZE_EVENT` event after resizing
++   the console to better propagate window size changes to console programs.
++   In particular, this affects WSL and Cygwin.
++   [#110](https://github.com/rprichard/winpty/issues/110)
++ * Better handling of resizing for certain full-screen programs, like
++   WSL less.
++   [#112](https://github.com/rprichard/winpty/issues/112)
++ * Hide the cursor if it's currently outside the console window.  This change
++   fixes an issue with Far Manager.
++   [#113](https://github.com/rprichard/winpty/issues/113)
++ * winpty now avoids using console fonts smaller than 5px high to improve
++   half-vs-full-width character handling.  See
++   https://github.com/Microsoft/vscode/issues/19665.
++   [b4db322010](https://github.com/rprichard/winpty/commit/b4db322010d2d897e6c496fefc4f0ecc9b84c2f3)
++
++Cygwin/MSYS adapter fix:
++
++ * The way the `winpty` Cygwin/MSYS2 adapter searches for the program to
++   launch changed.  It now resolves symlinks and searches the PATH explicitly.
++   [#81](https://github.com/rprichard/winpty/issues/81)
++   [#98](https://github.com/rprichard/winpty/issues/98)
++
++This release does not include binaries for the old MSYS1 project anymore.
++MSYS2 will continue to be supported.  See
++https://github.com/rprichard/winpty/issues/97.
++
++# Version 0.4.2 (2017-01-18)
++
++This release improves WSL support (i.e. Bash-on-Windows):
++
++ * winpty generates more correct input escape sequences for WSL programs that
++   enable an alternate input mode using DECCKM.  This bug affected arrow keys
++   and Home/End in WSL programs such as `vim`, `mc`, and `less`.
++   [#90](https://github.com/rprichard/winpty/issues/90)
++ * winpty now recognizes the `COMMON_LVB_REVERSE_VIDEO` and
++   `COMMON_LVB_UNDERSCORE` text attributes.  The Windows console uses these
++   attributes to implement the SGR.4(Underline) and SGR.7(Negative) modes in
++   its VT handling.  This change affects WSL pager status bars, man pages, etc.
++
++The build system no longer has a "version suffix" mechanism, so passing
++`VERSION_SUFFIX=<suffix>` to make or `-D VERSION_SUFFIX=<suffix>` to gyp now
++has no effect.  AFAIK, the mechanism was never used publicly.
++[67a34b6c03](https://github.com/rprichard/winpty/commit/67a34b6c03557a5c2e0a2bdd502c2210921d8f3e)
++
++# Version 0.4.1 (2017-01-03)
++
++Bug fixes:
++
++ * This version fixes a bug where the `winpty-agent.exe` process could read
++   past the end of a buffer.
++   [#94](https://github.com/rprichard/winpty/issues/94)
++
++# Version 0.4.0 (2016-06-28)
++
++The winpty library has a new API that should be easier for embedding.
++[880c00c69e](https://github.com/rprichard/winpty/commit/880c00c69eeca73643ddb576f02c5badbec81f56)
++
++User-visible changes:
++
++ * winpty now automatically puts the terminal into mouse mode when it detects
++   that the console has left QuickEdit mode.  The `--mouse` option still forces
++   the terminal into mouse mode.  In principle, an option could be added to
++   suppress terminal mode, but hopefully it won't be necessary.  There is a
++   script in the `misc` subdirectory, `misc/ConinMode.ps1`, that can change
++   the QuickEdit mode from the command-line.
++ * winpty now passes keyboard escapes to `bash.exe` in the Windows Subsystem
++   for Linux.
++   [#82](https://github.com/rprichard/winpty/issues/82)
++
++Bug fixes:
++
++ * By default, `winpty.dll` avoids calling `SetProcessWindowStation` within
++   the calling process.
++   [#58](https://github.com/rprichard/winpty/issues/58)
++ * Fixed an uninitialized memory bug that could have crashed winpty.
++   [#80](https://github.com/rprichard/winpty/issues/80)
++ * winpty now works better with very large and very small terminal windows.
++   It resizes the console font according to the number of columns.
++   [#61](https://github.com/rprichard/winpty/issues/61)
++ * winpty no longer uses Mark to freeze the console on Windows 10.  The Mark
++   command could interfere with the cursor position, corrupting the data in
++   the screen buffer.
++   [#79](https://github.com/rprichard/winpty/issues/79)
++
++# Version 0.3.0 (2016-05-20)
++
++User-visible changes:
++
++ * The UNIX adapter is renamed from `console.exe` to `winpty.exe` to be
++   consistent with MSYS2.  The name `winpty.exe` is less likely to conflict
++   with another program and is easier to search for online (e.g. for someone
++   unfamiliar with winpty).
++ * The UNIX adapter now clears the `TERM` variable.
++   [#43](https://github.com/rprichard/winpty/issues/43)
++ * An escape character appearing in a console screen buffer cell is converted
++   to a '?'.
++   [#47](https://github.com/rprichard/winpty/issues/47)
++
++Bug fixes:
++
++ * A major bug affecting XP users was fixed.
++   [#67](https://github.com/rprichard/winpty/issues/67)
++ * Fixed an incompatibility with ConEmu where winpty hung if ConEmu's
++   "Process 'start'" feature was enabled.
++   [#70](https://github.com/rprichard/winpty/issues/70)
++ * Fixed a bug where `cmd.exe` sometimes printed the message,
++   `Not enough storage is available to process this command.`.
++   [#74](https://github.com/rprichard/winpty/issues/74)
++
++Many changes internally:
++
++ * The codebase is switched from C++03 to C++11 and uses exceptions internally.
++   No exceptions are thrown across the C APIs defined in `winpty.h`.
++ * This version drops support for the original MinGW compiler packaged with
++   Cygwin (`i686-pc-mingw32-g++`).  The MinGW-w64 compiler is still supported,
++   as is the MinGW distributed at mingw.org.  Compiling with MSVC now requires
++   MSVC 2013 or newer.  Windows XP is still supported.
++   [ec3eae8df5](https://github.com/rprichard/winpty/commit/ec3eae8df5bbbb36d7628d168b0815638d122f37)
++ * Pipe security is improved.  winpty works harder to produce unique pipe names
++   and includes a random component in the name.  winpty secures pipes with a
++   DACL that prevents arbitrary users from connecting to its pipes.  winpty now
++   passes `PIPE_REJECT_REMOTE_CLIENTS` on Vista and up, and it verifies that
++   the pipe client PID is correct, again on Vista and up.  When connecting to a
++   named pipe, winpty uses the `SECURITY_IDENTIFICATION` flag to restrict
++   impersonation.  Previous versions *should* still be secure.
++ * `winpty-debugserver.exe` now has an `--everyone` flag that allows capturing
++   debug output from other users.
++ * The code now compiles cleanly with MSVC's "Security Development Lifecycle"
++   (`/SDL`) checks enabled.
++
++# Version 0.2.2 (2016-02-25)
++
++Minor bug fixes and enhancements:
++
++ * Fix a bug that generated spurious mouse input records when an incomplete
++   mouse escape sequence was seen.
++ * Fix a buffer overflow bug in `winpty-debugserver.exe` affecting messages of
++   exactly 4096 bytes.
++ * For MSVC builds, add a `src/configurations.gypi` file that can be included
++   on the gyp command-line to enable 32-bit and 64-bit builds.
++ * `winpty-agent --show-input` mode: Flush stdout after each line.
++ * Makefile builds: generate a `build/winpty.lib` import library to accompany
++   `build/winpty.dll`.
++
++# Version 0.2.1 (2015-12-19)
++
++ * The main project source was moved into a `src` directory for better code
++   organization and to fix
++   [#51](https://github.com/rprichard/winpty/issues/51).
++ * winpty recognizes many more escape sequences, including:
++    * putty/rxvt's F1-F4 keys
++      [#40](https://github.com/rprichard/winpty/issues/40)
++    * the Linux virtual console's F1-F5 keys
++    * the "application numpad" keys (e.g. enabled with DECPAM)
++ * Fixed handling of Shift-Alt-O and Alt-[.
++ * Added support for mouse input.  The UNIX adapter has a `--mouse` argument
++   that puts the terminal into mouse mode, but the agent recognizes mouse
++   input even without the argument.  The agent recognizes double-clicks using
++   Windows' double-click interval setting (i.e. GetDoubleClickTime).
++   [#57](https://github.com/rprichard/winpty/issues/57)
++
++Changes to debugging interfaces:
++
++ * The `WINPTY_DEBUG` variable is now a comma-separated list.  The old
++   behavior (i.e. tracing) is enabled with `WINPTY_DEBUG=trace`.
++ * The UNIX adapter program now has a `--showkey` argument that dumps input
++   bytes.
++ * The `winpty-agent.exe` program has a `--show-input` argument that dumps
++   `INPUT_RECORD` records.  (It omits mouse events unless `--with-mouse` is
++   also specified.)  The agent also responds to `WINPTY_DEBUG=trace,input`,
++   which logs input bytes and synthesized console events, and it responds to
++   `WINPTY_DEBUG=trace,dump_input_map`, which dumps the internal table of
++   escape sequences.
++
++# Version 0.2.0 (2015-11-13)
++
++No changes to the API, but many small changes to the implementation.  The big
++changes include:
++
++ * Support for 64-bit Cygwin and MSYS2
++ * Support for Windows 10
++ * Better Unicode support (especially East Asian languages)
++
++Details:
++
++ * The `configure` script recognizes 64-bit Cygwin and MSYS2 environments and
++   selects the appropriate compiler.
++ * winpty works much better with the upgraded console in Windows 10.  The
++   `conhost.exe` hang can still occur, but only with certain programs, and
++   is much less likely to occur.  With the new console, use Mark instead of
++   SelectAll, for better performance.
++   [#31](https://github.com/rprichard/winpty/issues/31)
++   [#30](https://github.com/rprichard/winpty/issues/30)
++   [#53](https://github.com/rprichard/winpty/issues/53)
++ * The UNIX adapter now calls `setlocale(LC_ALL, "")` to set the locale.
++ * Improved Unicode support.  When a console is started with an East Asian code
++   page, winpty now chooses an East Asian font rather than Consolas / Lucida
++   Console.  Selecting the right font helps synchronize character widths
++   between the console and terminal.  (It's not perfect, though.)
++   [#41](https://github.com/rprichard/winpty/issues/41)
++ * winpty now more-or-less works with programs that change the screen buffer
++   or resize the original screen buffer.  If the screen buffer height changes,
++   winpty switches to a "direct mode", where it makes no effort to track
++   scrolling.  In direct mode, it merely syncs snapshots of the console to the
++   terminal.  Caveats:
++    * Changing the screen buffer (i.e. `SetConsoleActiveScreenBuffer`)
++      breaks winpty on Windows 7.  This problem can eventually be mitigated,
++      but never completely fixed, due to Windows 7 bugginess.
++    * Resizing the original screen buffer can hang `conhost.exe` on Windows 10.
++      Enabling the legacy console is a workaround.
++    * If a program changes the screen buffer and then exits, relying on the OS
++      to restore the original screen buffer, that restoration probably will not
++      happen with winpty.  winpty's behavior can probably be improved here.
++ * Improved color handling:
++    * DkGray-on-Black text was previously hiddenly completely.  Now it is
++      output as DkGray, with a fallback to LtGray on terminals that don't
++      recognize the intense colors.
++      [#39](https://github.com/rprichard/winpty/issues/39).
++    * The console is always initialized to LtGray-on-Black, regardless of the
++      user setting, which matches the console color heuristic, which translates
++      LtGray-on-Black to "reset SGR parameters."
++ * Shift-Tab is recognized correctly now.
++   [#19](https://github.com/rprichard/winpty/issues/19)
++ * Add a `--version` argument to `winpty-agent.exe` and the UNIX adapter.  The
++   argument reports the nominal version (i.e. the `VERSION.txt`) file, with a
++   "VERSION_SUFFIX" appended (defaulted to `-dev`), and a git commit hash, if
++   the `git` command successfully reports a hash during the build.  The `git`
++   command is invoked by either `make` or `gyp`.
++ * The agent now combines `ReadConsoleOutputW` calls when it polls the console
++   buffer for changes, which may slightly reduce its CPU overhead.
++   [#44](https://github.com/rprichard/winpty/issues/44).
++ * A `gyp` file is added to help compile with MSVC.
++ * The code can now be compiled as C++11 code, though it isn't by default.
++   [bde8922e08](https://github.com/rprichard/winpty/commit/bde8922e08c3638e01ecc7b581b676c314163e3c)
++ * If winpty can't create a new window station, it charges ahead rather than
++   aborting.  This situation might happen if winpty were started from an SSH
++   session.
++ * Debugging improvements:
++    * `WINPTYDBG` is renamed to `WINPTY_DEBUG`, and a new `WINPTY_SHOW_CONSOLE`
++      variable keeps the underlying console visible.
++    * A `winpty-debugserver.exe` program is built and shipped by default.  It
++      collects the trace output enabled with `WINPTY_DEBUG`.
++ * The `Makefile` build of winpty now compiles `winpty-agent.exe` and
++   `winpty.dll` with -O2.
++
++# Version 0.1.1 (2012-07-28)
++
++Minor bugfix release.
++
++# Version 0.1 (2012-04-17)
++
++Initial release.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..5d47ff8c45ad40a08f7d6eb74f04acf695f74bfb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++0.4.4-dev
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6d37d65b091e429bdf34b6236d161933ade6bb78
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,167 @@@
++#!/bin/bash
++#
++# Copyright (c) 2011-2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++#
++# findTool(desc, commandList)
++#
++# Searches commandLine for the first command in the PATH and returns it.
++# Prints an error and aborts the script if no match is found.
++#
++FINDTOOL_OUT=""
++function findTool {
++    DESC=$1
++    OPTIONS=$2
++    for CMD in ${OPTIONS}; do
++        if (which $CMD &>/dev/null) then
++            echo "Found $DESC: $CMD"
++            FINDTOOL_OUT="$CMD"
++            return
++        fi
++    done
++    echo "Error: could not find $DESC.  One of these should be in your PATH:"
++    for CMD in ${OPTIONS}; do
++        echo " * $CMD"
++    done
++    exit 1
++}
++
++IS_CYGWIN=0
++IS_MSYS1=0
++IS_MSYS2=0
++
++# Link parts of the Cygwin binary statically to aid in redistribution?  The
++# binary still links dynamically against the main DLL.  The MinGW binaries are
++# also statically linked and therefore depend only on Windows DLLs.  I started
++# linking the Cygwin/MSYS binary statically, because G++ 4.7 changed the
++# Windows C++ ABI.
++UNIX_LDFLAGS_STATIC='-static -static-libgcc -static-libstdc++'
++
++# Detect the environment -- Cygwin or MSYS.
++case $(uname -s) in
++    CYGWIN*)
++        echo 'uname -s identifies a Cygwin environment.'
++        IS_CYGWIN=1
++          case $(uname -m) in
++            i686)
++                echo 'uname -m identifies an i686 environment.'
++                UNIX_CXX=i686-pc-cygwin-g++
++                MINGW_CXX=i686-w64-mingw32-g++
++                ;;
++            x86_64)
++                echo 'uname -m identifies an x86_64 environment.'
++                UNIX_CXX=x86_64-pc-cygwin-g++
++                MINGW_CXX=x86_64-w64-mingw32-g++
++                ;;
++            *)
++                echo 'Error: uname -m did not match either i686 or x86_64.'
++                exit 1
++                ;;
++          esac
++        ;;
++    MSYS*|MINGW*)
++        # MSYS2 notes:
++        #  - MSYS2 offers two shortcuts to open an environment:
++        #     - MinGW-w64 Win32 Shell.  This env reports a `uname -s` of
++        #       MINGW32_NT-6.1 on 32-bit Win7.  The MinGW-w64 compiler
++        #       (i686-w64-mingw32-g++.exe) is in the PATH.
++        #     - MSYS2 Shell.  `uname -s` instead reports MSYS_NT-6.1.
++        #       The i686-w64-mingw32-g++ compiler is not in the PATH.
++        #  - MSYS2 appears to use MinGW-w64, not the older mingw.org.
++        # MSYS notes:
++        #  - `uname -s` is always MINGW32_NT-6.1 on Win7.
++        echo 'uname -s identifies an MSYS/MSYS2 environment.'
++        case $(uname -m) in
++            i686)
++                echo 'uname -m identifies an i686 environment.'
++                UNIX_CXX=i686-pc-msys-g++
++                if echo "$(uname -r)" | grep '^1[.]' > /dev/null; then
++                    # The MSYS-targeting compiler for the original 32-bit-only
++                    # MSYS does not recognize the -static-libstdc++ flag, and
++                    # it does not work with -static, because it tries to link
++                    # statically with the core MSYS library and fails.
++                    #
++                    # Distinguish between the two using the major version
++                    # number of `uname -r`:
++                    #
++                    #   MSYS uname -r:  1.0.18(0.48/3/2)
++                    #   MSYS2 uname -r: 2.0.0(0.284/5/3)
++                    #
++                    # This is suboptimal because MSYS2 is not actually the
++                    # second version of MSYS--it's a brand-new fork of Cygwin.
++                    #
++                    IS_MSYS1=1
++                    UNIX_LDFLAGS_STATIC=
++                    MINGW_CXX=mingw32-g++
++                else
++                    IS_MSYS2=1
++                    MINGW_CXX=i686-w64-mingw32-g++.exe
++                fi
++                ;;
++            x86_64)
++                echo 'uname -m identifies an x86_64 environment.'
++                IS_MSYS2=1
++                UNIX_CXX=x86_64-pc-msys-g++
++                MINGW_CXX=x86_64-w64-mingw32-g++
++                ;;
++            *)
++                echo 'Error: uname -m did not match either i686 or x86_64.'
++                exit 1
++                ;;
++        esac
++        ;;
++    *)
++        echo 'Error: uname -s did not match either CYGWIN* or MINGW*.'
++        exit 1
++        ;;
++esac
++
++# Search the PATH and pick the first match.
++findTool "Cygwin/MSYS G++ compiler" "$UNIX_CXX"
++UNIX_CXX=$FINDTOOL_OUT
++findTool "MinGW G++ compiler" "$MINGW_CXX"
++MINGW_CXX=$FINDTOOL_OUT
++
++# Write config files.
++echo Writing config.mk
++echo UNIX_CXX=$UNIX_CXX > config.mk
++echo UNIX_LDFLAGS_STATIC=$UNIX_LDFLAGS_STATIC >> config.mk
++echo MINGW_CXX=$MINGW_CXX >> config.mk
++
++if test $IS_MSYS1 = 1; then
++    echo UNIX_CXXFLAGS += -DWINPTY_TARGET_MSYS1 >> config.mk
++    # The MSYS1 MinGW compiler has a bug that prevents inclusion of algorithm
++    # and math.h in normal C++11 mode.  The workaround is to enable the gnu++11
++    # mode instead.  The bug was fixed on 2015-07-31, but as of 2016-02-26, the
++    # fix apparently hasn't been released.  See
++    # http://ehc.ac/p/mingw/bugs/2250/.
++    echo MINGW_ENABLE_CXX11_FLAG := -std=gnu++11 >> config.mk
++fi
++
++if test -d .git -a -f .git/HEAD -a -f .git/index && git rev-parse HEAD >&/dev/null; then
++    echo "Commit info: git"
++    echo 'COMMIT_HASH = $(shell git rev-parse HEAD)' >> config.mk
++    echo 'COMMIT_HASH_DEP := config.mk .git/HEAD .git/index' >> config.mk
++else
++    echo "Commit info: none"
++    echo 'COMMIT_HASH := none' >> config.mk
++    echo 'COMMIT_HASH_DEP := config.mk' >> config.mk
++fi
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..23751645fa1eac0574999fda75bcff0a0f5845fc
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,2 @@@
++*.exe
++UnixEcho
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a5bb074826f105ba9b256eb7416dc23b4ffd7561
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,90 @@@
++#include <windows.h>
++#include <cassert>
++
++#include "TestUtil.cc"
++
++void dumpInfoToTrace() {
++    CONSOLE_SCREEN_BUFFER_INFO info;
++    assert(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info));
++    trace("win=(%d,%d,%d,%d)",
++        (int)info.srWindow.Left,
++        (int)info.srWindow.Top,
++        (int)info.srWindow.Right,
++        (int)info.srWindow.Bottom);
++    trace("buf=(%d,%d)",
++        (int)info.dwSize.X,
++        (int)info.dwSize.Y);
++    trace("cur=(%d,%d)",
++        (int)info.dwCursorPosition.X,
++        (int)info.dwCursorPosition.Y);
++}
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    setWindowPos(0, 0, 1, 1);
++
++    if (false) {
++        // Reducing the buffer height can move the window up.
++        setBufferSize(80, 25);
++        setWindowPos(0, 20, 80, 5);
++        Sleep(2000);
++        setBufferSize(80, 10);
++    }
++
++    if (false) {
++        // Reducing the buffer height moves the window up and the buffer
++        // contents up too.
++        setBufferSize(80, 25);
++        setWindowPos(0, 20, 80, 5);
++        setCursorPos(0, 20);
++        printf("TEST1\nTEST2\nTEST3\nTEST4\n");
++        fflush(stdout);
++        Sleep(2000);
++        setBufferSize(80, 10);
++    }
++
++    if (false) {
++        // Reducing the buffer width can move the window left.
++        setBufferSize(80, 25);
++        setWindowPos(40, 0, 40, 25);
++        Sleep(2000);
++        setBufferSize(60, 25);
++    }
++
++    if (false) {
++        // Sometimes the buffer contents are shifted up; sometimes they're
++        // shifted down.  It seems to depend on the cursor position?
++
++        // setBufferSize(80, 25);
++        // setWindowPos(0, 20, 80, 5);
++        // setCursorPos(0, 20);
++        // printf("TESTa\nTESTb\nTESTc\nTESTd\nTESTe");
++        // fflush(stdout);
++        // setCursorPos(0, 0);
++        // printf("TEST1\nTEST2\nTEST3\nTEST4\nTEST5");
++        // fflush(stdout);
++        // setCursorPos(0, 24);
++        // Sleep(5000);
++        // setBufferSize(80, 24);
++
++        setBufferSize(80, 20);
++        setWindowPos(0, 10, 80, 10);
++        setCursorPos(0, 18);
++
++        printf("TEST1\nTEST2");
++        fflush(stdout);
++        setCursorPos(0, 18);
++
++        Sleep(2000);
++        setBufferSize(80, 18);
++    }
++
++    dumpInfoToTrace();
++    Sleep(30000);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..701a2cb4a3c2b58ed749775fba9fe879f7f3c428
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,53 @@@
++// A test program for CreateConsoleScreenBuffer / SetConsoleActiveScreenBuffer
++//
++
++#include <windows.h>
++#include <stdio.h>
++#include <conio.h>
++#include <io.h>
++#include <cassert>
++
++#include "TestUtil.cc"
++
++int main()
++{
++    HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
++    HANDLE childBuffer = CreateConsoleScreenBuffer(
++            GENERIC_READ | GENERIC_WRITE,
++            FILE_SHARE_READ | FILE_SHARE_WRITE,
++            NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
++
++    SetConsoleActiveScreenBuffer(childBuffer);
++
++    while (true) {
++        char buf[1024];
++        CONSOLE_SCREEN_BUFFER_INFO info;
++
++        assert(GetConsoleScreenBufferInfo(origBuffer, &info));
++        trace("child.size=(%d,%d)", (int)info.dwSize.X, (int)info.dwSize.Y);
++        trace("child.cursor=(%d,%d)", (int)info.dwCursorPosition.X, (int)info.dwCursorPosition.Y);
++        trace("child.window=(%d,%d,%d,%d)",
++            (int)info.srWindow.Left, (int)info.srWindow.Top,
++            (int)info.srWindow.Right, (int)info.srWindow.Bottom);
++        trace("child.maxSize=(%d,%d)", (int)info.dwMaximumWindowSize.X, (int)info.dwMaximumWindowSize.Y);
++
++        int ch = getch();
++        sprintf(buf, "%02x\n", ch);
++        DWORD actual = 0;
++        WriteFile(childBuffer, buf, strlen(buf), &actual, NULL);
++        if (ch == 0x1b/*ESC*/ || ch == 0x03/*CTRL-C*/)
++            break;
++
++        if (ch == 'b') {
++            setBufferSize(origBuffer, 40, 25);
++        } else if (ch == 'w') {
++            setWindowPos(origBuffer, 1, 1, 38, 23);
++        } else if (ch == 'c') {
++            setCursorPos(origBuffer, 10, 10);
++        }
++    }
++
++    SetConsoleActiveScreenBuffer(origBuffer);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..f95f8c84caa87043f89546d309772dcf86b7f253
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,72 @@@
++/*
++ * Demonstrates that console clearing sets each cell's character to SP, not
++ * NUL, and it sets the attribute of each cell to the current text attribute.
++ *
++ * This confirms the MSDN instruction in the "Clearing the Screen" article.
++ * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682022(v=vs.85).aspx
++ * It advises using GetConsoleScreenBufferInfo to get the current text
++ * attribute, then FillConsoleOutputCharacter and FillConsoleOutputAttribute to
++ * write to the console buffer.
++ */
++
++#include <windows.h>
++
++#include <cassert>
++#include <cstdio>
++#include <cstdlib>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    SetConsoleTextAttribute(conout, 0x24);
++    system("cls");
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(80, 25);
++    setWindowPos(0, 0, 80, 25);
++
++    CHAR_INFO buf;
++    COORD bufSize = { 1, 1 };
++    COORD bufCoord = { 0, 0 };
++    SMALL_RECT rect = { 5, 5, 5, 5 };
++    BOOL ret;
++    DWORD actual;
++    COORD writeCoord = { 5, 5 };
++
++    // After cls, each cell's character is a space, and its attributes are the
++    // default text attributes.
++    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
++    assert(ret && buf.Char.UnicodeChar == L' ' && buf.Attributes == 0x24);
++
++    // Nevertheless, it is possible to change a cell to NUL.
++    ret = FillConsoleOutputCharacterW(conout, L'\0', 1, writeCoord, &actual);
++    assert(ret && actual == 1);
++    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
++    assert(ret && buf.Char.UnicodeChar == L'\0' && buf.Attributes == 0x24);
++
++    // As well as a 0 attribute.  (As one would expect, the cell is
++    // black-on-black.)
++    ret = FillConsoleOutputAttribute(conout, 0, 1, writeCoord, &actual);
++    assert(ret && actual == 1);
++    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
++    assert(ret && buf.Char.UnicodeChar == L'\0' && buf.Attributes == 0);
++    ret = FillConsoleOutputCharacterW(conout, L'X', 1, writeCoord, &actual);
++    assert(ret && actual == 1);
++    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
++    assert(ret && buf.Char.UnicodeChar == L'X' && buf.Attributes == 0);
++
++    // The 'X' is invisible.
++    countDown(3);
++
++    ret = FillConsoleOutputAttribute(conout, 0x42, 1, writeCoord, &actual);
++    assert(ret && actual == 1);
++
++    countDown(5);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1e1428d8b0c3d15df4652cb1b12615ff84f04f5e
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,117 @@@
++#include <windows.h>
++
++#include <errno.h>
++#include <stdio.h>
++#include <stdlib.h>
++
++#include <string>
++#include <vector>
++
++static HANDLE getConin() {
++    HANDLE conin = GetStdHandle(STD_INPUT_HANDLE);
++    if (conin == INVALID_HANDLE_VALUE) {
++        fprintf(stderr, "error: cannot get stdin\n");
++        exit(1);
++    }
++    return conin;
++}
++
++static DWORD getConsoleMode() {
++    DWORD mode = 0;
++    if (!GetConsoleMode(getConin(), &mode)) {
++        fprintf(stderr, "error: GetConsoleMode failed (is stdin a console?)\n");
++        exit(1);
++    }
++    return mode;
++}
++
++static void setConsoleMode(DWORD mode) {
++    if (!SetConsoleMode(getConin(), mode)) {
++        fprintf(stderr, "error: SetConsoleMode failed (is stdin a console?)\n");
++        exit(1);
++    }
++}
++
++static long parseInt(const std::string &s) {
++    errno = 0;
++    char *endptr = nullptr;
++    long result = strtol(s.c_str(), &endptr, 0);
++    if (errno != 0 || !endptr || *endptr != '\0') {
++        fprintf(stderr, "error: could not parse integral argument '%s'\n", s.c_str());
++        exit(1);
++    }
++    return result;
++}
++
++static void usage() {
++    printf("Usage: ConinMode [verb] [options]\n");
++    printf("Verbs:\n");
++    printf("    [info]      Dumps info about mode flags.\n");
++    printf("    get         Prints the mode DWORD.\n");
++    printf("    set VALUE   Sets the mode to VALUE, which can be decimal, hex, or octal.\n");
++    printf("    set VALUE MASK\n");
++    printf("                Same as `set VALUE`, but only alters the bits in MASK.\n");
++    exit(1);
++}
++
++struct {
++    const char *name;
++    DWORD value;
++} kInputFlags[] = {
++    "ENABLE_PROCESSED_INPUT",           ENABLE_PROCESSED_INPUT,         // 0x0001
++    "ENABLE_LINE_INPUT",                ENABLE_LINE_INPUT,              // 0x0002
++    "ENABLE_ECHO_INPUT",                ENABLE_ECHO_INPUT,              // 0x0004
++    "ENABLE_WINDOW_INPUT",              ENABLE_WINDOW_INPUT,            // 0x0008
++    "ENABLE_MOUSE_INPUT",               ENABLE_MOUSE_INPUT,             // 0x0010
++    "ENABLE_INSERT_MODE",               ENABLE_INSERT_MODE,             // 0x0020
++    "ENABLE_QUICK_EDIT_MODE",           ENABLE_QUICK_EDIT_MODE,         // 0x0040
++    "ENABLE_EXTENDED_FLAGS",            ENABLE_EXTENDED_FLAGS,          // 0x0080
++    "ENABLE_VIRTUAL_TERMINAL_INPUT", 0x0200/*ENABLE_VIRTUAL_TERMINAL_INPUT*/, // 0x0200
++};
++
++int main(int argc, char *argv[]) {
++    std::vector<std::string> args;
++    for (size_t i = 1; i < argc; ++i) {
++        args.push_back(argv[i]);
++    }
++
++    if (args.empty() || args.size() == 1 && args[0] == "info") {
++        DWORD mode = getConsoleMode();
++        printf("mode: 0x%lx\n", mode);
++        for (const auto &flag : kInputFlags) {
++            printf("%-29s 0x%04lx %s\n", flag.name, flag.value, flag.value & mode ? "ON" : "off");
++            mode &= ~flag.value;
++        }
++        for (int i = 0; i < 32; ++i) {
++            if (mode & (1u << i)) {
++                printf("Unrecognized flag: %04x\n", (1u << i));
++            }
++        }
++        return 0;
++    }
++
++    const auto verb = args[0];
++
++    if (verb == "set") {
++        if (args.size() == 2) {
++            const DWORD newMode = parseInt(args[1]);
++            setConsoleMode(newMode);
++        } else if (args.size() == 3) {
++            const DWORD mode = parseInt(args[1]);
++            const DWORD mask = parseInt(args[2]);
++            const int newMode = (getConsoleMode() & ~mask) | (mode & mask);
++            setConsoleMode(newMode);
++        } else {
++            usage();
++        }
++    } else if (verb == "get") {
++        if (args.size() != 1) {
++            usage();
++        }
++        printf("0x%lx\n", getConsoleMode());
++    } else {
++        usage();
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ecfe8f039e4fc4ce9c31b685fd6fb6b344f73794
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,116 @@@
++#
++# PowerShell script for controlling the console QuickEdit and InsertMode flags.
++#
++# Turn QuickEdit off to interact with mouse-driven console programs.
++#
++# Usage:
++#
++# powershell .\ConinMode.ps1 [Options]
++#
++# Options:
++#   -QuickEdit [on/off]
++#   -InsertMode [on/off]
++#   -Mode [integer]
++#
++
++param (
++    [ValidateSet("on", "off")][string] $QuickEdit,
++    [ValidateSet("on", "off")][string] $InsertMode,
++    [int] $Mode
++)
++
++$signature = @'
++[DllImport("kernel32.dll", SetLastError = true)]
++public static extern IntPtr GetStdHandle(int nStdHandle);
++
++[DllImport("kernel32.dll", SetLastError = true)]
++public static extern uint GetConsoleMode(
++    IntPtr hConsoleHandle,
++    out uint lpMode);
++
++[DllImport("kernel32.dll", SetLastError = true)]
++public static extern uint SetConsoleMode(
++    IntPtr hConsoleHandle,
++    uint dwMode);
++
++public const int STD_INPUT_HANDLE = -10;
++public const int ENABLE_INSERT_MODE = 0x0020;
++public const int ENABLE_QUICK_EDIT_MODE = 0x0040;
++public const int ENABLE_EXTENDED_FLAGS = 0x0080;
++'@
++
++$WinAPI = Add-Type -MemberDefinition $signature `
++    -Name WinAPI -Namespace ConinModeScript `
++    -PassThru
++
++function GetConIn {
++    $ret = $WinAPI::GetStdHandle($WinAPI::STD_INPUT_HANDLE)
++    if ($ret -eq -1) {
++        throw "error: cannot get stdin"
++    }
++    return $ret
++}
++
++function GetConsoleMode {
++    $conin = GetConIn
++    $mode = 0
++    $ret = $WinAPI::GetConsoleMode($conin, [ref]$mode)
++    if ($ret -eq 0) {
++        throw "GetConsoleMode failed (is stdin a console?)"
++    }
++    return $mode
++}
++
++function SetConsoleMode($mode) {
++    $conin = GetConIn
++    $ret = $WinAPI::SetConsoleMode($conin, $mode)
++    if ($ret -eq 0) {
++        throw "SetConsoleMode failed (is stdin a console?)"
++    }
++}
++
++$oldMode = GetConsoleMode
++$newMode = $oldMode
++$doingSomething = $false
++
++if ($PSBoundParameters.ContainsKey("Mode")) {
++    $newMode = $Mode
++    $doingSomething = $true
++}
++
++if ($QuickEdit + $InsertMode -ne "") {
++    if (!($newMode -band $WinAPI::ENABLE_EXTENDED_FLAGS)) {
++        # We can't enable an extended flag without overwriting the existing
++        # QuickEdit/InsertMode flags.  AFAICT, there is no way to query their
++        # existing values, so at least we can choose sensible defaults.
++        $newMode = $newMode -bor $WinAPI::ENABLE_EXTENDED_FLAGS
++        $newMode = $newMode -bor $WinAPI::ENABLE_QUICK_EDIT_MODE
++        $newMode = $newMode -bor $WinAPI::ENABLE_INSERT_MODE
++        $doingSomething = $true
++    }
++}
++
++if ($QuickEdit -eq "on") {
++    $newMode = $newMode -bor $WinAPI::ENABLE_QUICK_EDIT_MODE
++    $doingSomething = $true
++} elseif ($QuickEdit -eq "off") {
++    $newMode = $newMode -band (-bnot $WinAPI::ENABLE_QUICK_EDIT_MODE)
++    $doingSomething = $true
++}
++
++if ($InsertMode -eq "on") {
++    $newMode = $newMode -bor $WinAPI::ENABLE_INSERT_MODE
++    $doingSomething = $true
++} elseif ($InsertMode -eq "off") {
++    $newMode = $newMode -band (-bnot $WinAPI::ENABLE_INSERT_MODE)
++    $doingSomething = $true
++}
++
++if ($doingSomething) {
++    echo "old mode: $oldMode"
++    SetConsoleMode $newMode
++    $newMode = GetConsoleMode
++    echo "new mode: $newMode"
++} else {
++    echo "mode: $oldMode"
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..100e0c7bea9c5999f9620709d7fad15c9ae97733
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,113 @@@
++#include <windows.h>
++
++#include <errno.h>
++#include <stdio.h>
++#include <stdlib.h>
++
++#include <string>
++#include <vector>
++
++static HANDLE getConout() {
++    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++    if (conout == INVALID_HANDLE_VALUE) {
++        fprintf(stderr, "error: cannot get stdout\n");
++        exit(1);
++    }
++    return conout;
++}
++
++static DWORD getConsoleMode() {
++    DWORD mode = 0;
++    if (!GetConsoleMode(getConout(), &mode)) {
++        fprintf(stderr, "error: GetConsoleMode failed (is stdout a console?)\n");
++        exit(1);
++    }
++    return mode;
++}
++
++static void setConsoleMode(DWORD mode) {
++    if (!SetConsoleMode(getConout(), mode)) {
++        fprintf(stderr, "error: SetConsoleMode failed (is stdout a console?)\n");
++        exit(1);
++    }
++}
++
++static long parseInt(const std::string &s) {
++    errno = 0;
++    char *endptr = nullptr;
++    long result = strtol(s.c_str(), &endptr, 0);
++    if (errno != 0 || !endptr || *endptr != '\0') {
++        fprintf(stderr, "error: could not parse integral argument '%s'\n", s.c_str());
++        exit(1);
++    }
++    return result;
++}
++
++static void usage() {
++    printf("Usage: ConoutMode [verb] [options]\n");
++    printf("Verbs:\n");
++    printf("    [info]      Dumps info about mode flags.\n");
++    printf("    get         Prints the mode DWORD.\n");
++    printf("    set VALUE   Sets the mode to VALUE, which can be decimal, hex, or octal.\n");
++    printf("    set VALUE MASK\n");
++    printf("                Same as `set VALUE`, but only alters the bits in MASK.\n");
++    exit(1);
++}
++
++struct {
++    const char *name;
++    DWORD value;
++} kOutputFlags[] = {
++    "ENABLE_PROCESSED_OUTPUT",          ENABLE_PROCESSED_OUTPUT,        // 0x0001
++    "ENABLE_WRAP_AT_EOL_OUTPUT",        ENABLE_WRAP_AT_EOL_OUTPUT,      // 0x0002
++    "ENABLE_VIRTUAL_TERMINAL_PROCESSING", 0x0004/*ENABLE_VIRTUAL_TERMINAL_PROCESSING*/, // 0x0004
++    "DISABLE_NEWLINE_AUTO_RETURN",      0x0008/*DISABLE_NEWLINE_AUTO_RETURN*/, // 0x0008
++    "ENABLE_LVB_GRID_WORLDWIDE",        0x0010/*ENABLE_LVB_GRID_WORLDWIDE*/, //0x0010
++};
++
++int main(int argc, char *argv[]) {
++    std::vector<std::string> args;
++    for (size_t i = 1; i < argc; ++i) {
++        args.push_back(argv[i]);
++    }
++
++    if (args.empty() || args.size() == 1 && args[0] == "info") {
++        DWORD mode = getConsoleMode();
++        printf("mode: 0x%lx\n", mode);
++        for (const auto &flag : kOutputFlags) {
++            printf("%-34s 0x%04lx %s\n", flag.name, flag.value, flag.value & mode ? "ON" : "off");
++            mode &= ~flag.value;
++        }
++        for (int i = 0; i < 32; ++i) {
++            if (mode & (1u << i)) {
++                printf("Unrecognized flag: %04x\n", (1u << i));
++            }
++        }
++        return 0;
++    }
++
++    const auto verb = args[0];
++
++    if (verb == "set") {
++        if (args.size() == 2) {
++            const DWORD newMode = parseInt(args[1]);
++            setConsoleMode(newMode);
++        } else if (args.size() == 3) {
++            const DWORD mode = parseInt(args[1]);
++            const DWORD mask = parseInt(args[2]);
++            const int newMode = (getConsoleMode() & ~mask) | (mode & mask);
++            setConsoleMode(newMode);
++        } else {
++            usage();
++        }
++    } else if (verb == "get") {
++        if (args.size() != 1) {
++            usage();
++        }
++        printf("0x%lx\n", getConsoleMode());
++    } else {
++        usage();
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cd12df8924a3c94384fcb46d258f1ca48f35f034
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,42 @@@
++#!python
++# Run with native CPython.  Needs pywin32 extensions.
++
++# Copyright (c) 2011-2012 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++import winerror
++import win32pipe
++import win32file
++import win32api
++import sys
++import pywintypes
++import time
++
++if len(sys.argv) != 2:
++    print("Usage: %s message" % sys.argv[0])
++    sys.exit(1)
++
++message = "[%05.3f %s]: %s" % (time.time() % 100000, sys.argv[0], sys.argv[1])
++
++win32pipe.CallNamedPipe(
++    "\\\\.\\pipe\\DebugServer",
++    message.encode(),
++    16,
++    win32pipe.NMPWAIT_WAIT_FOREVER)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3fc068bae701eb762f2fd6764ccd94e5efd2218a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,63 @@@
++#!python
++#
++# Run with native CPython.  Needs pywin32 extensions.
++
++# Copyright (c) 2011-2012 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++import win32pipe
++import win32api
++import win32file
++import time
++import threading
++import sys
++
++# A message may not be larger than this size.
++MSG_SIZE=4096
++
++serverPipe = win32pipe.CreateNamedPipe(
++    "\\\\.\\pipe\\DebugServer",
++    win32pipe.PIPE_ACCESS_DUPLEX,
++    win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE,
++    win32pipe.PIPE_UNLIMITED_INSTANCES,
++    MSG_SIZE,
++    MSG_SIZE,
++    10 * 1000,
++    None)
++while True:
++    win32pipe.ConnectNamedPipe(serverPipe, None)
++    (ret, data) = win32file.ReadFile(serverPipe, MSG_SIZE)
++    print(data.decode())
++    sys.stdout.flush()
++
++    # The client uses CallNamedPipe to send its message.  CallNamedPipe waits
++    # for a reply message.  If I send a reply, however, using WriteFile, then
++    # sometimes WriteFile fails with:
++    #     pywintypes.error: (232, 'WriteFile', 'The pipe is being closed.')
++    # I can't figure out how to write a strictly correct pipe server, but if
++    # I comment out the WriteFile line, then everything seems to work.  I
++    # think the DisconnectNamedPipe call aborts the client's CallNamedPipe
++    # call normally.
++
++    try:
++        win32file.WriteFile(serverPipe, b'OK')
++    except:
++        pass
++    win32pipe.DisconnectNamedPipe(serverPipe)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..40049961b5c98203fa2352c6674285d8bd061e67
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,5 @@@
++#!/usr/bin/env python
++import sys
++
++for i in range(1, int(sys.argv[1]) + 1):
++    print i, "X" * 78
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..37914dac26874348c6f4ffedfad54190790be0b9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,46 @@@
++Note regarding ENABLE_EXTENDED_FLAGS (2016-05-30)
++
++There is a complicated interaction between the ENABLE_EXTENDED_FLAGS flag
++and the ENABLE_QUICK_EDIT_MODE and ENABLE_INSERT_MODE flags (presumably for
++backwards compatibility?).  I studied the behavior on Windows 7 and Windows
++10, with both the old and new consoles, and I didn't see any differences
++between versions.  Here's what I seemed to observe:
++
++ - The console has three flags internally:
++    - QuickEdit
++    - InsertMode
++    - ExtendedFlags
++
++ - SetConsoleMode psuedocode:
++      void SetConsoleMode(..., DWORD mode) {
++        ExtendedFlags = (mode & (ENABLE_EXTENDED_FLAGS
++                                  | ENABLE_QUICK_EDIT_MODE
++                                  | ENABLE_INSERT_MODE    )) != 0;
++        if (ExtendedFlags) {
++          QuickEdit = (mode & ENABLE_QUICK_EDIT_MODE) != 0;
++          InsertMode = (mode & ENABLE_INSERT_MODE) != 0;
++        }
++      }
++
++ - Setting QuickEdit or InsertMode from the properties dialog GUI does not
++   affect the ExtendedFlags setting -- it simply toggles the one flag.
++
++ - GetConsoleMode psuedocode:
++      GetConsoleMode(..., DWORD *result) {
++        if (ExtendedFlags) {
++          *result |= ENABLE_EXTENDED_FLAGS;
++          if (QuickEdit) { *result |= ENABLE_QUICK_EDIT_MODE; }
++          if (InsertMode) { *result |= ENABLE_INSERT_MODE; }
++        }
++      }
++
++Effectively, the ExtendedFlags flags controls whether the other two flags
++are visible/controlled by the user application.  If they aren't visible,
++though, there is no way for the user application to make them visible,
++except by overwriting their values!  Calling SetConsoleMode with just
++ENABLE_EXTENDED_FLAGS would clear the extended flags we want to read.
++
++Consequently, if a program temporarily alters the QuickEdit flag (e.g. to
++enable mouse input), it cannot restore the original values of the QuickEdit
++and InsertMode flags, UNLESS every other console program cooperates by
++keeping the ExtendedFlags flag set.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..067bd3824a8ce434c47ce4347da20ecdeda1248a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,528 @@@
++==================================
++Code Page 437, Consolas font
++==================================
++
++Options: -face "Consolas" -family 0x36
++Chars: A2 A3 2014 3044 30FC 4000
++
++FontSurvey "-face \"Consolas\" -family 0x36"
++
++Windows 7
++---------
++
++Size   1: 1,3     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 1,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 2,5     BAD  (HHHHHH)
++Size   6: 3,6     BAD  (HHHHHH)
++Size   7: 3,6     BAD  (HHHHHH)
++Size   8: 4,8     BAD  (HHHHHH)
++Size   9: 4,9     BAD  (HHHHHH)
++Size  10: 5,10    BAD  (HHHHHH)
++Size  11: 5,11    BAD  (HHHHHH)
++Size  12: 6,12    BAD  (HHHHHH)
++Size  13: 6,13    BAD  (HHHHHH)
++Size  14: 7,14    BAD  (HHHHHH)
++Size  15: 7,15    BAD  (HHHHHH)
++Size  16: 8,16    BAD  (HHHHHH)
++Size  17: 8,17    BAD  (HHHHHH)
++Size  18: 8,18    BAD  (HHHHHH)
++Size  19: 9,19    BAD  (HHHHHH)
++Size  20: 9,20    BAD  (HHHHHH)
++Size  21: 10,22   BAD  (HHHHHH)
++Size  22: 10,22   BAD  (HHHHHH)
++Size  23: 11,23   BAD  (HHHHHH)
++Size  24: 11,24   BAD  (HHHHHH)
++Size  25: 12,25   BAD  (HHHHHH)
++Size  26: 12,26   BAD  (HHHHHH)
++Size  27: 13,27   BAD  (HHHHHH)
++Size  28: 13,28   BAD  (HHHHHH)
++Size  29: 14,29   BAD  (HHHHHH)
++Size  30: 14,30   BAD  (HHHHHH)
++Size  31: 15,31   BAD  (HHHHHH)
++Size  32: 15,32   BAD  (HHHHHH)
++Size  33: 15,33   BAD  (HHHHHH)
++Size  34: 16,34   BAD  (HHHHHH)
++Size  35: 16,36   BAD  (HHHHHH)
++Size  36: 17,36   BAD  (HHHHHH)
++Size  37: 17,37   BAD  (HHHHHH)
++Size  38: 18,38   BAD  (HHHHHH)
++Size  39: 18,39   BAD  (HHHHHH)
++Size  40: 19,40   BAD  (HHHHHH)
++Size  41: 19,41   BAD  (HHHHHH)
++Size  42: 20,42   BAD  (HHHHHH)
++Size  43: 20,43   BAD  (HHHHHH)
++Size  44: 21,44   BAD  (HHHHHH)
++Size  45: 21,45   BAD  (HHHHHH)
++Size  46: 22,46   BAD  (HHHHHH)
++Size  47: 22,47   BAD  (HHHHHH)
++Size  48: 23,48   BAD  (HHHHHH)
++Size  49: 23,49   BAD  (HHHHHH)
++Size  50: 23,50   BAD  (HHHHHH)
++Size  51: 24,51   BAD  (HHHHHH)
++Size  52: 24,52   BAD  (HHHHHH)
++Size  53: 25,53   BAD  (HHHHHH)
++Size  54: 25,54   BAD  (HHHHHH)
++Size  55: 26,55   BAD  (HHHHHH)
++Size  56: 26,56   BAD  (HHHHHH)
++Size  57: 27,57   BAD  (HHHHHH)
++Size  58: 27,58   BAD  (HHHHHH)
++Size  59: 28,59   BAD  (HHHHHH)
++Size  60: 28,60   BAD  (HHHHHH)
++Size  61: 29,61   BAD  (HHHHHH)
++Size  62: 29,62   BAD  (HHHHHH)
++Size  63: 30,64   BAD  (HHHHHH)
++Size  64: 30,64   BAD  (HHHHHH)
++Size  65: 31,65   BAD  (HHHHHH)
++Size  66: 31,66   BAD  (HHHHHH)
++Size  67: 31,67   BAD  (HHHHHH)
++Size  68: 32,68   BAD  (HHHHHH)
++Size  69: 32,69   BAD  (HHHHHH)
++Size  70: 33,70   BAD  (HHHHHH)
++Size  71: 33,71   BAD  (HHHHHH)
++Size  72: 34,72   BAD  (HHHHHH)
++Size  73: 34,73   BAD  (HHHHHH)
++Size  74: 35,74   BAD  (HHHHHH)
++Size  75: 35,75   BAD  (HHHHHH)
++Size  76: 36,76   BAD  (HHHHHH)
++Size  77: 36,77   BAD  (HHHHHH)
++Size  78: 37,78   BAD  (HHHHHH)
++Size  79: 37,79   BAD  (HHHHHH)
++Size  80: 38,80   BAD  (HHHHHH)
++Size  81: 38,81   BAD  (HHHHHH)
++Size  82: 39,82   BAD  (HHHHHH)
++Size  83: 39,83   BAD  (HHHHHH)
++Size  84: 39,84   BAD  (HHHHHH)
++Size  85: 40,85   BAD  (HHHHHH)
++Size  86: 40,86   BAD  (HHHHHH)
++Size  87: 41,87   BAD  (HHHHHH)
++Size  88: 41,88   BAD  (HHHHHH)
++Size  89: 42,89   BAD  (HHHHHH)
++Size  90: 42,90   BAD  (HHHHHH)
++Size  91: 43,91   BAD  (HHHHHH)
++Size  92: 43,92   BAD  (HHHHHH)
++Size  93: 44,93   BAD  (HHHHHH)
++Size  94: 44,94   BAD  (HHHHHH)
++Size  95: 45,95   BAD  (HHHHHH)
++Size  96: 45,96   BAD  (HHHHHH)
++Size  97: 46,97   BAD  (HHHHHH)
++Size  98: 46,98   BAD  (HHHHHH)
++Size  99: 46,99   BAD  (HHHHHH)
++Size 100: 47,100  BAD  (HHHHHH)
++
++Windows 8
++---------
++
++Size   1: 1,3     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 1,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 2,5     BAD  (HHHHHH)
++Size   6: 3,6     BAD  (HHHHHH)
++Size   7: 3,6     BAD  (HHHHHH)
++Size   8: 4,8     BAD  (HHHHHH)
++Size   9: 4,9     BAD  (HHHHHH)
++Size  10: 5,10    BAD  (HHHHHH)
++Size  11: 5,11    BAD  (HHHHHH)
++Size  12: 6,12    BAD  (HHHHHH)
++Size  13: 6,13    BAD  (HHHHHH)
++Size  14: 7,14    BAD  (HHHHHH)
++Size  15: 7,15    BAD  (HHHHHH)
++Size  16: 8,16    BAD  (HHHHHH)
++Size  17: 8,17    BAD  (HHHHHH)
++Size  18: 8,18    BAD  (HHHHHH)
++Size  19: 9,19    BAD  (HHHHHH)
++Size  20: 9,20    BAD  (HHHHHH)
++Size  21: 10,22   BAD  (HHHHHH)
++Size  22: 10,22   BAD  (HHHHHH)
++Size  23: 11,23   BAD  (HHHHHH)
++Size  24: 11,24   BAD  (HHHHHH)
++Size  25: 12,25   BAD  (HHHHHH)
++Size  26: 12,26   BAD  (HHHHHH)
++Size  27: 13,27   BAD  (HHHHHH)
++Size  28: 13,28   BAD  (HHHHHH)
++Size  29: 14,29   BAD  (HHHHHH)
++Size  30: 14,30   BAD  (HHHHHH)
++Size  31: 15,31   BAD  (HHHHHH)
++Size  32: 15,32   BAD  (HHHHHH)
++Size  33: 15,33   BAD  (HHHHHH)
++Size  34: 16,34   BAD  (HHHHHH)
++Size  35: 16,36   BAD  (HHHHHH)
++Size  36: 17,36   BAD  (HHHHHH)
++Size  37: 17,37   BAD  (HHHHHH)
++Size  38: 18,38   BAD  (HHHHHH)
++Size  39: 18,39   BAD  (HHHHHH)
++Size  40: 19,40   BAD  (HHHHHH)
++Size  41: 19,41   BAD  (HHHHHH)
++Size  42: 20,42   BAD  (HHHHHH)
++Size  43: 20,43   BAD  (HHHHHH)
++Size  44: 21,44   BAD  (HHHHHH)
++Size  45: 21,45   BAD  (HHHHHH)
++Size  46: 22,46   BAD  (HHHHHH)
++Size  47: 22,47   BAD  (HHHHHH)
++Size  48: 23,48   BAD  (HHHHHH)
++Size  49: 23,49   BAD  (HHHHHH)
++Size  50: 23,50   BAD  (HHHHHH)
++Size  51: 24,51   BAD  (HHHHHH)
++Size  52: 24,52   BAD  (HHHHHH)
++Size  53: 25,53   BAD  (HHHHHH)
++Size  54: 25,54   BAD  (HHHHHH)
++Size  55: 26,55   BAD  (HHHHHH)
++Size  56: 26,56   BAD  (HHHHHH)
++Size  57: 27,57   BAD  (HHHHHH)
++Size  58: 27,58   BAD  (HHHHHH)
++Size  59: 28,59   BAD  (HHHHHH)
++Size  60: 28,60   BAD  (HHHHHH)
++Size  61: 29,61   BAD  (HHHHHH)
++Size  62: 29,62   BAD  (HHHHHH)
++Size  63: 30,64   BAD  (HHHHHH)
++Size  64: 30,64   BAD  (HHHHHH)
++Size  65: 31,65   BAD  (HHHHHH)
++Size  66: 31,66   BAD  (HHHHHH)
++Size  67: 31,67   BAD  (HHHHHH)
++Size  68: 32,68   BAD  (HHHHHH)
++Size  69: 32,69   BAD  (HHHHHH)
++Size  70: 33,70   BAD  (HHHHHH)
++Size  71: 33,71   BAD  (HHHHHH)
++Size  72: 34,72   BAD  (HHHHHH)
++Size  73: 34,73   BAD  (HHHHHH)
++Size  74: 35,74   BAD  (HHHHHH)
++Size  75: 35,75   BAD  (HHHHHH)
++Size  76: 36,76   BAD  (HHHHHH)
++Size  77: 36,77   BAD  (HHHHHH)
++Size  78: 37,78   BAD  (HHHHHH)
++Size  79: 37,79   BAD  (HHHHHH)
++Size  80: 38,80   BAD  (HHHHHH)
++Size  81: 38,81   BAD  (HHHHHH)
++Size  82: 39,82   BAD  (HHHHHH)
++Size  83: 39,83   BAD  (HHHHHH)
++Size  84: 39,84   BAD  (HHHHHH)
++Size  85: 40,85   BAD  (HHHHHH)
++Size  86: 40,86   BAD  (HHHHHH)
++Size  87: 41,87   BAD  (HHHHHH)
++Size  88: 41,88   BAD  (HHHHHH)
++Size  89: 42,89   BAD  (HHHHHH)
++Size  90: 42,90   BAD  (HHHHHH)
++Size  91: 43,91   BAD  (HHHHHH)
++Size  92: 43,92   BAD  (HHHHHH)
++Size  93: 44,93   BAD  (HHHHHH)
++Size  94: 44,94   BAD  (HHHHHH)
++Size  95: 45,95   BAD  (HHHHHH)
++Size  96: 45,96   BAD  (HHHHHH)
++Size  97: 46,97   BAD  (HHHHHH)
++Size  98: 46,98   BAD  (HHHHHH)
++Size  99: 46,99   BAD  (HHHHHH)
++Size 100: 47,100  BAD  (HHHHHH)
++
++Windows 8.1
++-----------
++
++Size   1: 1,3     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 1,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 2,5     BAD  (HHHHHH)
++Size   6: 3,6     BAD  (HHHHHH)
++Size   7: 3,6     BAD  (HHHHHH)
++Size   8: 4,8     BAD  (HHHHHH)
++Size   9: 4,9     BAD  (HHHHHH)
++Size  10: 5,10    BAD  (HHHHHH)
++Size  11: 5,11    BAD  (HHHHHH)
++Size  12: 6,12    BAD  (HHHHHH)
++Size  13: 6,13    BAD  (HHHHHH)
++Size  14: 7,14    BAD  (HHHHHH)
++Size  15: 7,15    BAD  (HHHHHH)
++Size  16: 8,16    BAD  (HHHHHH)
++Size  17: 8,17    BAD  (HHHHHH)
++Size  18: 8,18    BAD  (HHHHHH)
++Size  19: 9,19    BAD  (HHHHHH)
++Size  20: 9,20    BAD  (HHHHHH)
++Size  21: 10,22   BAD  (HHHHHH)
++Size  22: 10,22   BAD  (HHHHHH)
++Size  23: 11,23   BAD  (HHHHHH)
++Size  24: 11,24   BAD  (HHHHHH)
++Size  25: 12,25   BAD  (HHHHHH)
++Size  26: 12,26   BAD  (HHHHHH)
++Size  27: 13,27   BAD  (HHHHHH)
++Size  28: 13,28   BAD  (HHHHHH)
++Size  29: 14,29   BAD  (HHHHHH)
++Size  30: 14,30   BAD  (HHHHHH)
++Size  31: 15,31   BAD  (HHHHHH)
++Size  32: 15,32   BAD  (HHHHHH)
++Size  33: 15,33   BAD  (HHHHHH)
++Size  34: 16,34   BAD  (HHHHHH)
++Size  35: 16,36   BAD  (HHHHHH)
++Size  36: 17,36   BAD  (HHHHHH)
++Size  37: 17,37   BAD  (HHHHHH)
++Size  38: 18,38   BAD  (HHHHHH)
++Size  39: 18,39   BAD  (HHHHHH)
++Size  40: 19,40   BAD  (HHHHHH)
++Size  41: 19,41   BAD  (HHHHHH)
++Size  42: 20,42   BAD  (HHHHHH)
++Size  43: 20,43   BAD  (HHHHHH)
++Size  44: 21,44   BAD  (HHHHHH)
++Size  45: 21,45   BAD  (HHHHHH)
++Size  46: 22,46   BAD  (HHHHHH)
++Size  47: 22,47   BAD  (HHHHHH)
++Size  48: 23,48   BAD  (HHHHHH)
++Size  49: 23,49   BAD  (HHHHHH)
++Size  50: 23,50   BAD  (HHHHHH)
++Size  51: 24,51   BAD  (HHHHHH)
++Size  52: 24,52   BAD  (HHHHHH)
++Size  53: 25,53   BAD  (HHHHHH)
++Size  54: 25,54   BAD  (HHHHHH)
++Size  55: 26,55   BAD  (HHHHHH)
++Size  56: 26,56   BAD  (HHHHHH)
++Size  57: 27,57   BAD  (HHHHHH)
++Size  58: 27,58   BAD  (HHHHHH)
++Size  59: 28,59   BAD  (HHHHHH)
++Size  60: 28,60   BAD  (HHHHHH)
++Size  61: 29,61   BAD  (HHHHHH)
++Size  62: 29,62   BAD  (HHHHHH)
++Size  63: 30,64   BAD  (HHHHHH)
++Size  64: 30,64   BAD  (HHHHHH)
++Size  65: 31,65   BAD  (HHHHHH)
++Size  66: 31,66   BAD  (HHHHHH)
++Size  67: 31,67   BAD  (HHHHHH)
++Size  68: 32,68   BAD  (HHHHHH)
++Size  69: 32,69   BAD  (HHHHHH)
++Size  70: 33,70   BAD  (HHHHHH)
++Size  71: 33,71   BAD  (HHHHHH)
++Size  72: 34,72   BAD  (HHHHHH)
++Size  73: 34,73   BAD  (HHHHHH)
++Size  74: 35,74   BAD  (HHHHHH)
++Size  75: 35,75   BAD  (HHHHHH)
++Size  76: 36,76   BAD  (HHHHHH)
++Size  77: 36,77   BAD  (HHHHHH)
++Size  78: 37,78   BAD  (HHHHHH)
++Size  79: 37,79   BAD  (HHHHHH)
++Size  80: 38,80   BAD  (HHHHHH)
++Size  81: 38,81   BAD  (HHHHHH)
++Size  82: 39,82   BAD  (HHHHHH)
++Size  83: 39,83   BAD  (HHHHHH)
++Size  84: 39,84   BAD  (HHHHHH)
++Size  85: 40,85   BAD  (HHHHHH)
++Size  86: 40,86   BAD  (HHHHHH)
++Size  87: 41,87   BAD  (HHHHHH)
++Size  88: 41,88   BAD  (HHHHHH)
++Size  89: 42,89   BAD  (HHHHHH)
++Size  90: 42,90   BAD  (HHHHHH)
++Size  91: 43,91   BAD  (HHHHHH)
++Size  92: 43,92   BAD  (HHHHHH)
++Size  93: 44,93   BAD  (HHHHHH)
++Size  94: 44,94   BAD  (HHHHHH)
++Size  95: 45,95   BAD  (HHHHHH)
++Size  96: 45,96   BAD  (HHHHHH)
++Size  97: 46,97   BAD  (HHHHHH)
++Size  98: 46,98   BAD  (HHHHHH)
++Size  99: 46,99   BAD  (HHHHHH)
++Size 100: 47,100  BAD  (HHHHHH)
++
++Windows 10 14342 Old Console
++----------------------------
++
++Size   1: 1,3     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 1,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 2,5     BAD  (HHHHHH)
++Size   6: 3,6     BAD  (HHHHHH)
++Size   7: 3,6     BAD  (HHHHHH)
++Size   8: 4,8     BAD  (HHHHHH)
++Size   9: 4,9     BAD  (HHHHHH)
++Size  10: 5,10    BAD  (HHHHHH)
++Size  11: 5,11    BAD  (HHHHHH)
++Size  12: 6,12    BAD  (HHHHHH)
++Size  13: 6,13    BAD  (HHHHHH)
++Size  14: 7,14    BAD  (HHHHHH)
++Size  15: 7,15    BAD  (HHHHHH)
++Size  16: 8,16    BAD  (HHHHHH)
++Size  17: 8,17    BAD  (HHHHHH)
++Size  18: 8,18    BAD  (HHHHHH)
++Size  19: 9,19    BAD  (HHHHHH)
++Size  20: 9,20    BAD  (HHHHHH)
++Size  21: 10,22   BAD  (HHHHHH)
++Size  22: 10,22   BAD  (HHHHHH)
++Size  23: 11,23   BAD  (HHHHHH)
++Size  24: 11,24   BAD  (HHHHHH)
++Size  25: 12,25   BAD  (HHHHHH)
++Size  26: 12,26   BAD  (HHHHHH)
++Size  27: 13,27   BAD  (HHHHHH)
++Size  28: 13,28   BAD  (HHHHHH)
++Size  29: 14,29   BAD  (HHHHHH)
++Size  30: 14,30   BAD  (HHHHHH)
++Size  31: 15,31   BAD  (HHHHHH)
++Size  32: 15,32   BAD  (HHHHHH)
++Size  33: 15,33   BAD  (HHHHHH)
++Size  34: 16,34   BAD  (HHHHHH)
++Size  35: 16,36   BAD  (HHHHHH)
++Size  36: 17,36   BAD  (HHHHHH)
++Size  37: 17,37   BAD  (HHHHHH)
++Size  38: 18,38   BAD  (HHHHHH)
++Size  39: 18,39   BAD  (HHHHHH)
++Size  40: 19,40   BAD  (HHHHHH)
++Size  41: 19,41   BAD  (HHHHHH)
++Size  42: 20,42   BAD  (HHHHHH)
++Size  43: 20,43   BAD  (HHHHHH)
++Size  44: 21,44   BAD  (HHHHHH)
++Size  45: 21,45   BAD  (HHHHHH)
++Size  46: 22,46   BAD  (HHHHHH)
++Size  47: 22,47   BAD  (HHHHHH)
++Size  48: 23,48   BAD  (HHHHHH)
++Size  49: 23,49   BAD  (HHHHHH)
++Size  50: 23,50   BAD  (HHHHHH)
++Size  51: 24,51   BAD  (HHHHHH)
++Size  52: 24,52   BAD  (HHHHHH)
++Size  53: 25,53   BAD  (HHHHHH)
++Size  54: 25,54   BAD  (HHHHHH)
++Size  55: 26,55   BAD  (HHHHHH)
++Size  56: 26,56   BAD  (HHHHHH)
++Size  57: 27,57   BAD  (HHHHHH)
++Size  58: 27,58   BAD  (HHHHHH)
++Size  59: 28,59   BAD  (HHHHHH)
++Size  60: 28,60   BAD  (HHHHHH)
++Size  61: 29,61   BAD  (HHHHHH)
++Size  62: 29,62   BAD  (HHHHHH)
++Size  63: 30,64   BAD  (HHHHHH)
++Size  64: 30,64   BAD  (HHHHHH)
++Size  65: 31,65   BAD  (HHHHHH)
++Size  66: 31,66   BAD  (HHHHHH)
++Size  67: 31,67   BAD  (HHHHHH)
++Size  68: 32,68   BAD  (HHHHHH)
++Size  69: 32,69   BAD  (HHHHHH)
++Size  70: 33,70   BAD  (HHHHHH)
++Size  71: 33,71   BAD  (HHHHHH)
++Size  72: 34,72   BAD  (HHHHHH)
++Size  73: 34,73   BAD  (HHHHHH)
++Size  74: 35,74   BAD  (HHHHHH)
++Size  75: 35,75   BAD  (HHHHHH)
++Size  76: 36,76   BAD  (HHHHHH)
++Size  77: 36,77   BAD  (HHHHHH)
++Size  78: 37,78   BAD  (HHHHHH)
++Size  79: 37,79   BAD  (HHHHHH)
++Size  80: 38,80   BAD  (HHHHHH)
++Size  81: 38,81   BAD  (HHHHHH)
++Size  82: 39,82   BAD  (HHHHHH)
++Size  83: 39,83   BAD  (HHHHHH)
++Size  84: 39,84   BAD  (HHHHHH)
++Size  85: 40,85   BAD  (HHHHHH)
++Size  86: 40,86   BAD  (HHHHHH)
++Size  87: 41,87   BAD  (HHHHHH)
++Size  88: 41,88   BAD  (HHHHHH)
++Size  89: 42,89   BAD  (HHHHHH)
++Size  90: 42,90   BAD  (HHHHHH)
++Size  91: 43,91   BAD  (HHHHHH)
++Size  92: 43,92   BAD  (HHHHHH)
++Size  93: 44,93   BAD  (HHHHHH)
++Size  94: 44,94   BAD  (HHHHHH)
++Size  95: 45,95   BAD  (HHHHHH)
++Size  96: 45,96   BAD  (HHHHHH)
++Size  97: 46,97   BAD  (HHHHHH)
++Size  98: 46,98   BAD  (HHHHHH)
++Size  99: 46,99   BAD  (HHHHHH)
++Size 100: 47,100  BAD  (HHHHHH)
++
++Windows 10 14342 New Console
++----------------------------
++
++Size   1: 1,1     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 1,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 2,5     BAD  (HHHHHH)
++Size   6: 3,6     BAD  (HHHHHH)
++Size   7: 3,7     BAD  (HHHHHH)
++Size   8: 4,8     BAD  (HHHHHH)
++Size   9: 4,9     BAD  (HHHHHH)
++Size  10: 5,10    BAD  (HHHHHH)
++Size  11: 5,11    BAD  (HHHHHH)
++Size  12: 6,12    BAD  (HHHHHH)
++Size  13: 6,13    BAD  (HHHHHH)
++Size  14: 7,14    BAD  (HHHHHH)
++Size  15: 7,15    BAD  (HHHHHH)
++Size  16: 8,16    BAD  (HHHHHH)
++Size  17: 8,17    BAD  (HHHHHH)
++Size  18: 8,18    BAD  (HHHHHH)
++Size  19: 9,19    BAD  (HHHHHH)
++Size  20: 9,20    BAD  (HHHHHH)
++Size  21: 10,21   BAD  (HHHHHH)
++Size  22: 10,22   BAD  (HHHHHH)
++Size  23: 11,23   BAD  (HHHHHH)
++Size  24: 11,24   BAD  (HHHHHH)
++Size  25: 12,25   BAD  (HHHHHH)
++Size  26: 12,26   BAD  (HHHHHH)
++Size  27: 13,27   BAD  (HHHHHH)
++Size  28: 13,28   BAD  (HHHHHH)
++Size  29: 14,29   BAD  (HHHHHH)
++Size  30: 14,30   BAD  (HHHHHH)
++Size  31: 15,31   BAD  (HHHHHH)
++Size  32: 15,32   BAD  (HHHHHH)
++Size  33: 15,33   BAD  (HHHHHH)
++Size  34: 16,34   BAD  (HHHHHH)
++Size  35: 16,35   BAD  (HHHHHH)
++Size  36: 17,36   BAD  (HHHHHH)
++Size  37: 17,37   BAD  (HHHHHH)
++Size  38: 18,38   BAD  (HHHHHH)
++Size  39: 18,39   BAD  (HHHHHH)
++Size  40: 19,40   BAD  (HHHHHH)
++Size  41: 19,41   BAD  (HHHHHH)
++Size  42: 20,42   BAD  (HHHHHH)
++Size  43: 20,43   BAD  (HHHHHH)
++Size  44: 21,44   BAD  (HHHHHH)
++Size  45: 21,45   BAD  (HHHHHH)
++Size  46: 22,46   BAD  (HHHHHH)
++Size  47: 22,47   BAD  (HHHHHH)
++Size  48: 23,48   BAD  (HHHHHH)
++Size  49: 23,49   BAD  (HHHHHH)
++Size  50: 23,50   BAD  (HHHHHH)
++Size  51: 24,51   BAD  (HHHHHH)
++Size  52: 24,52   BAD  (HHHHHH)
++Size  53: 25,53   BAD  (HHHHHH)
++Size  54: 25,54   BAD  (HHHHHH)
++Size  55: 26,55   BAD  (HHHHHH)
++Size  56: 26,56   BAD  (HHHHHH)
++Size  57: 27,57   BAD  (HHHHHH)
++Size  58: 27,58   BAD  (HHHHHH)
++Size  59: 28,59   BAD  (HHHHHH)
++Size  60: 28,60   BAD  (HHHHHH)
++Size  61: 29,61   BAD  (HHHHHH)
++Size  62: 29,62   BAD  (HHHHHH)
++Size  63: 30,63   BAD  (HHHHHH)
++Size  64: 30,64   BAD  (HHHHHH)
++Size  65: 31,65   BAD  (HHHHHH)
++Size  66: 31,66   BAD  (HHHHHH)
++Size  67: 31,67   BAD  (HHHHHH)
++Size  68: 32,68   BAD  (HHHHHH)
++Size  69: 32,69   BAD  (HHHHHH)
++Size  70: 33,70   BAD  (HHHHHH)
++Size  71: 33,71   BAD  (HHHHHH)
++Size  72: 34,72   BAD  (HHHHHH)
++Size  73: 34,73   BAD  (HHHHHH)
++Size  74: 35,74   BAD  (HHHHHH)
++Size  75: 35,75   BAD  (HHHHHH)
++Size  76: 36,76   BAD  (HHHHHH)
++Size  77: 36,77   BAD  (HHHHHH)
++Size  78: 37,78   BAD  (HHHHHH)
++Size  79: 37,79   BAD  (HHHHHH)
++Size  80: 38,80   BAD  (HHHHHH)
++Size  81: 38,81   BAD  (HHHHHH)
++Size  82: 39,82   BAD  (HHHHHH)
++Size  83: 39,83   BAD  (HHHHHH)
++Size  84: 39,84   BAD  (HHHHHH)
++Size  85: 40,85   BAD  (HHHHHH)
++Size  86: 40,86   BAD  (HHHHHH)
++Size  87: 41,87   BAD  (HHHHHH)
++Size  88: 41,88   BAD  (HHHHHH)
++Size  89: 42,89   BAD  (HHHHHH)
++Size  90: 42,90   BAD  (HHHHHH)
++Size  91: 43,91   BAD  (HHHHHH)
++Size  92: 43,92   BAD  (HHHHHH)
++Size  93: 44,93   BAD  (HHHHHH)
++Size  94: 44,94   BAD  (HHHHHH)
++Size  95: 45,95   BAD  (HHHHHH)
++Size  96: 45,96   BAD  (HHHHHH)
++Size  97: 46,97   BAD  (HHHHHH)
++Size  98: 46,98   BAD  (HHHHHH)
++Size  99: 46,99   BAD  (HHHHHH)
++Size 100: 47,100  BAD  (HHHHHH)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0eed93ad989e6218043a7205259bc75e50a4648c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,633 @@@
++==================================
++Code Page 437, Lucida Console font
++==================================
++
++Options: -face "Lucida Console" -family 0x36
++Chars: A2 A3 2014 3044 30FC 4000
++
++FontSurvey "-face \"Lucida Console\" -family 0x36"
++
++Vista
++-----
++
++Size   1: 1,2     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 2,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 3,5     BAD  (HHHHHH)
++Size   6: 4,6     BAD  (HHHHHH)
++Size   7: 4,7     BAD  (HHHHHH)
++Size   8: 5,8     BAD  (HHHHHH)
++Size   9: 5,9     BAD  (HHHHHH)
++Size  10: 6,10    BAD  (HHHHHH)
++Size  11: 7,11    BAD  (HHHHHH)
++Size  12: 7,12    BAD  (HHHHHH)
++Size  13: 8,13    BAD  (HHHHHH)
++Size  14: 8,14    BAD  (HHHHHH)
++Size  15: 9,15    BAD  (HHHHHH)
++Size  16: 10,16   BAD  (HHHHHH)
++Size  17: 10,17   BAD  (HHHHHH)
++Size  18: 11,18   BAD  (HHHHHH)
++Size  19: 11,19   BAD  (HHHHHH)
++Size  20: 12,20   BAD  (HHHHHH)
++Size  21: 13,21   BAD  (HHHHHH)
++Size  22: 13,22   BAD  (HHHHHH)
++Size  23: 14,23   BAD  (HHHHHH)
++Size  24: 14,24   BAD  (HHHHHH)
++Size  25: 15,25   BAD  (HHHHHH)
++Size  26: 16,26   BAD  (HHHHHH)
++Size  27: 16,27   BAD  (HHHHHH)
++Size  28: 17,28   BAD  (HHHHHH)
++Size  29: 17,29   BAD  (HHHHHH)
++Size  30: 18,30   BAD  (HHHHHH)
++Size  31: 19,31   BAD  (HHHHHH)
++Size  32: 19,32   BAD  (HHHHHH)
++Size  33: 20,33   BAD  (HHHHHH)
++Size  34: 20,34   BAD  (HHHHHH)
++Size  35: 21,35   BAD  (HHHHHH)
++Size  36: 22,36   BAD  (HHHHHH)
++Size  37: 22,37   BAD  (HHHHHH)
++Size  38: 23,38   BAD  (HHHHHH)
++Size  39: 23,39   BAD  (HHHHHH)
++Size  40: 24,40   BAD  (HHHHHH)
++Size  41: 25,41   BAD  (HHHHHH)
++Size  42: 25,42   BAD  (HHHHHH)
++Size  43: 26,43   BAD  (HHHHHH)
++Size  44: 27,44   BAD  (HHHHHH)
++Size  45: 27,45   BAD  (HHHHHH)
++Size  46: 28,46   BAD  (HHHHHH)
++Size  47: 28,47   BAD  (HHHHHH)
++Size  48: 29,48   BAD  (HHHHHH)
++Size  49: 30,49   BAD  (HHHHHH)
++Size  50: 30,50   BAD  (HHHHHH)
++Size  51: 31,51   BAD  (HHHHHH)
++Size  52: 31,52   BAD  (HHHHHH)
++Size  53: 32,53   BAD  (HHHHHH)
++Size  54: 33,54   BAD  (HHHHHH)
++Size  55: 33,55   BAD  (HHHHHH)
++Size  56: 34,56   BAD  (HHHHHH)
++Size  57: 34,57   BAD  (HHHHHH)
++Size  58: 35,58   BAD  (HHHHHH)
++Size  59: 36,59   BAD  (HHHHHH)
++Size  60: 36,60   BAD  (HHHHHH)
++Size  61: 37,61   BAD  (HHHHHH)
++Size  62: 37,62   BAD  (HHHHHH)
++Size  63: 38,63   BAD  (HHHHHH)
++Size  64: 39,65   BAD  (HHHHHH)
++Size  65: 39,65   BAD  (HHHHHH)
++Size  66: 40,66   BAD  (HHHHHH)
++Size  67: 40,67   BAD  (HHHHHH)
++Size  68: 41,68   BAD  (HHHHHH)
++Size  69: 42,69   BAD  (HHHHHH)
++Size  70: 42,70   BAD  (HHHHHH)
++Size  71: 43,71   BAD  (HHHHHH)
++Size  72: 43,72   BAD  (HHHHHH)
++Size  73: 44,73   BAD  (HHHHHH)
++Size  74: 45,74   BAD  (HHHHHH)
++Size  75: 45,75   BAD  (HHHHHH)
++Size  76: 46,76   BAD  (HHHHHH)
++Size  77: 46,77   BAD  (HHHHHH)
++Size  78: 47,78   BAD  (HHHHHH)
++Size  79: 48,79   BAD  (HHHHHH)
++Size  80: 48,80   BAD  (HHHHHH)
++Size  81: 49,81   BAD  (HHHHHH)
++Size  82: 49,82   BAD  (HHHHHH)
++Size  83: 50,83   BAD  (HHHHHH)
++Size  84: 51,84   BAD  (HHHHHH)
++Size  85: 51,85   BAD  (HHHHHH)
++Size  86: 52,86   BAD  (HHHHHH)
++Size  87: 52,87   BAD  (HHHHHH)
++Size  88: 53,88   BAD  (HHHHHH)
++Size  89: 54,89   BAD  (HHHHHH)
++Size  90: 54,90   BAD  (HHHHHH)
++Size  91: 55,91   BAD  (HHHHHH)
++Size  92: 55,92   BAD  (HHHHHH)
++Size  93: 56,93   BAD  (HHHHHH)
++Size  94: 57,94   BAD  (HHHHHH)
++Size  95: 57,95   BAD  (HHHHHH)
++Size  96: 58,96   BAD  (HHHHHH)
++Size  97: 58,97   BAD  (HHHHHH)
++Size  98: 59,98   BAD  (HHHHHH)
++Size  99: 60,99   BAD  (HHHHHH)
++Size 100: 60,100  BAD  (HHHHHH)
++
++
++Windows 7
++---------
++
++Size   1: 1,2     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 2,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 3,5     BAD  (HHHHHH)
++Size   6: 4,6     BAD  (HHHHHH)
++Size   7: 4,7     BAD  (HHHHHH)
++Size   8: 5,8     BAD  (HHHHHH)
++Size   9: 5,9     BAD  (HHHHHH)
++Size  10: 6,10    BAD  (HHHHHH)
++Size  11: 7,11    BAD  (HHHHHH)
++Size  12: 7,12    BAD  (HHHHHH)
++Size  13: 8,13    BAD  (HHHHHH)
++Size  14: 8,14    BAD  (HHHHHH)
++Size  15: 9,15    BAD  (HHHHHH)
++Size  16: 10,16   BAD  (HHHHHH)
++Size  17: 10,17   BAD  (HHHHHH)
++Size  18: 11,18   BAD  (HHHHHH)
++Size  19: 11,19   BAD  (HHHHHH)
++Size  20: 12,20   BAD  (HHHHHH)
++Size  21: 13,21   BAD  (HHHHHH)
++Size  22: 13,22   BAD  (HHHHHH)
++Size  23: 14,23   BAD  (HHHHHH)
++Size  24: 14,24   BAD  (HHHHHH)
++Size  25: 15,25   BAD  (HHHHHH)
++Size  26: 16,26   BAD  (HHHHHH)
++Size  27: 16,27   BAD  (HHHHHH)
++Size  28: 17,28   BAD  (HHHHHH)
++Size  29: 17,29   BAD  (HHHHHH)
++Size  30: 18,30   BAD  (HHHHHH)
++Size  31: 19,31   BAD  (HHHHHH)
++Size  32: 19,32   BAD  (HHHHHH)
++Size  33: 20,33   BAD  (HHHHHH)
++Size  34: 20,34   BAD  (HHHHHH)
++Size  35: 21,35   BAD  (HHHHHH)
++Size  36: 22,36   BAD  (HHHHHH)
++Size  37: 22,37   BAD  (HHHHHH)
++Size  38: 23,38   BAD  (HHHHHH)
++Size  39: 23,39   BAD  (HHHHHH)
++Size  40: 24,40   BAD  (HHHHHH)
++Size  41: 25,41   BAD  (HHHHHH)
++Size  42: 25,42   BAD  (HHHHHH)
++Size  43: 26,43   BAD  (HHHHHH)
++Size  44: 27,44   BAD  (HHHHHH)
++Size  45: 27,45   BAD  (HHHHHH)
++Size  46: 28,46   BAD  (HHHHHH)
++Size  47: 28,47   BAD  (HHHHHH)
++Size  48: 29,48   BAD  (HHHHHH)
++Size  49: 30,49   BAD  (HHHHHH)
++Size  50: 30,50   BAD  (HHHHHH)
++Size  51: 31,51   BAD  (HHHHHH)
++Size  52: 31,52   BAD  (HHHHHH)
++Size  53: 32,53   BAD  (HHHHHH)
++Size  54: 33,54   BAD  (HHHHHH)
++Size  55: 33,55   BAD  (HHHHHH)
++Size  56: 34,56   BAD  (HHHHHH)
++Size  57: 34,57   BAD  (HHHHHH)
++Size  58: 35,58   BAD  (HHHHHH)
++Size  59: 36,59   BAD  (HHHHHH)
++Size  60: 36,60   BAD  (HHHHHH)
++Size  61: 37,61   BAD  (HHHHHH)
++Size  62: 37,62   BAD  (HHHHHH)
++Size  63: 38,63   BAD  (HHHHHH)
++Size  64: 39,65   BAD  (HHHHHH)
++Size  65: 39,65   BAD  (HHHHHH)
++Size  66: 40,66   BAD  (HHHHHH)
++Size  67: 40,67   BAD  (HHHHHH)
++Size  68: 41,68   BAD  (HHHHHH)
++Size  69: 42,69   BAD  (HHHHHH)
++Size  70: 42,70   BAD  (HHHHHH)
++Size  71: 43,71   BAD  (HHHHHH)
++Size  72: 43,72   BAD  (HHHHHH)
++Size  73: 44,73   BAD  (HHHHHH)
++Size  74: 45,74   BAD  (HHHHHH)
++Size  75: 45,75   BAD  (HHHHHH)
++Size  76: 46,76   BAD  (HHHHHH)
++Size  77: 46,77   BAD  (HHHHHH)
++Size  78: 47,78   BAD  (HHHHHH)
++Size  79: 48,79   BAD  (HHHHHH)
++Size  80: 48,80   BAD  (HHHHHH)
++Size  81: 49,81   BAD  (HHHHHH)
++Size  82: 49,82   BAD  (HHHHHH)
++Size  83: 50,83   BAD  (HHHHHH)
++Size  84: 51,84   BAD  (HHHHHH)
++Size  85: 51,85   BAD  (HHHHHH)
++Size  86: 52,86   BAD  (HHHHHH)
++Size  87: 52,87   BAD  (HHHHHH)
++Size  88: 53,88   BAD  (HHHHHH)
++Size  89: 54,89   BAD  (HHHHHH)
++Size  90: 54,90   BAD  (HHHHHH)
++Size  91: 55,91   BAD  (HHHHHH)
++Size  92: 55,92   BAD  (HHHHHH)
++Size  93: 56,93   BAD  (HHHHHH)
++Size  94: 57,94   BAD  (HHHHHH)
++Size  95: 57,95   BAD  (HHHHHH)
++Size  96: 58,96   BAD  (HHHHHH)
++Size  97: 58,97   BAD  (HHHHHH)
++Size  98: 59,98   BAD  (HHHHHH)
++Size  99: 60,99   BAD  (HHHHHH)
++Size 100: 60,100  BAD  (HHHHHH)
++
++Windows 8
++---------
++
++Size   1: 1,2     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 2,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 3,5     BAD  (HHHHHH)
++Size   6: 4,6     BAD  (HHHHHH)
++Size   7: 4,7     BAD  (HHHHHH)
++Size   8: 5,8     BAD  (HHHHHH)
++Size   9: 5,9     BAD  (HHHHHH)
++Size  10: 6,10    BAD  (HHHHHH)
++Size  11: 7,11    BAD  (HHHHHH)
++Size  12: 7,12    BAD  (HHHHHH)
++Size  13: 8,13    BAD  (HHHHHH)
++Size  14: 8,14    BAD  (HHHHHH)
++Size  15: 9,15    BAD  (HHHHHH)
++Size  16: 10,16   BAD  (HHHHHH)
++Size  17: 10,17   BAD  (HHHHHH)
++Size  18: 11,18   BAD  (HHHHHH)
++Size  19: 11,19   BAD  (HHHHHH)
++Size  20: 12,20   BAD  (HHHHHH)
++Size  21: 13,21   BAD  (HHHHHH)
++Size  22: 13,22   BAD  (HHHHHH)
++Size  23: 14,23   BAD  (HHHHHH)
++Size  24: 14,24   BAD  (HHHHHH)
++Size  25: 15,25   BAD  (HHHHHH)
++Size  26: 16,26   BAD  (HHHHHH)
++Size  27: 16,27   BAD  (HHHHHH)
++Size  28: 17,28   BAD  (HHHHHH)
++Size  29: 17,29   BAD  (HHHHHH)
++Size  30: 18,30   BAD  (HHHHHH)
++Size  31: 19,31   BAD  (HHHHHH)
++Size  32: 19,32   BAD  (HHHHHH)
++Size  33: 20,33   BAD  (HHHHHH)
++Size  34: 20,34   BAD  (HHHHHH)
++Size  35: 21,35   BAD  (HHHHHH)
++Size  36: 22,36   BAD  (HHHHHH)
++Size  37: 22,37   BAD  (HHHHHH)
++Size  38: 23,38   BAD  (HHHHHH)
++Size  39: 23,39   BAD  (HHHHHH)
++Size  40: 24,40   BAD  (HHHHHH)
++Size  41: 25,41   BAD  (HHHHHH)
++Size  42: 25,42   BAD  (HHHHHH)
++Size  43: 26,43   BAD  (HHHHHH)
++Size  44: 27,44   BAD  (HHHHHH)
++Size  45: 27,45   BAD  (HHHHHH)
++Size  46: 28,46   BAD  (HHHHHH)
++Size  47: 28,47   BAD  (HHHHHH)
++Size  48: 29,48   BAD  (HHHHHH)
++Size  49: 30,49   BAD  (HHHHHH)
++Size  50: 30,50   BAD  (HHHHHH)
++Size  51: 31,51   BAD  (HHHHHH)
++Size  52: 31,52   BAD  (HHHHHH)
++Size  53: 32,53   BAD  (HHHHHH)
++Size  54: 33,54   BAD  (HHHHHH)
++Size  55: 33,55   BAD  (HHHHHH)
++Size  56: 34,56   BAD  (HHHHHH)
++Size  57: 34,57   BAD  (HHHHHH)
++Size  58: 35,58   BAD  (HHHHHH)
++Size  59: 36,59   BAD  (HHHHHH)
++Size  60: 36,60   BAD  (HHHHHH)
++Size  61: 37,61   BAD  (HHHHHH)
++Size  62: 37,62   BAD  (HHHHHH)
++Size  63: 38,63   BAD  (HHHHHH)
++Size  64: 39,65   BAD  (HHHHHH)
++Size  65: 39,65   BAD  (HHHHHH)
++Size  66: 40,66   BAD  (HHHHHH)
++Size  67: 40,67   BAD  (HHHHHH)
++Size  68: 41,68   BAD  (HHHHHH)
++Size  69: 42,69   BAD  (HHHHHH)
++Size  70: 42,70   BAD  (HHHHHH)
++Size  71: 43,71   BAD  (HHHHHH)
++Size  72: 43,72   BAD  (HHHHHH)
++Size  73: 44,73   BAD  (HHHHHH)
++Size  74: 45,74   BAD  (HHHHHH)
++Size  75: 45,75   BAD  (HHHHHH)
++Size  76: 46,76   BAD  (HHHHHH)
++Size  77: 46,77   BAD  (HHHHHH)
++Size  78: 47,78   BAD  (HHHHHH)
++Size  79: 48,79   BAD  (HHHHHH)
++Size  80: 48,80   BAD  (HHHHHH)
++Size  81: 49,81   BAD  (HHHHHH)
++Size  82: 49,82   BAD  (HHHHHH)
++Size  83: 50,83   BAD  (HHHHHH)
++Size  84: 51,84   BAD  (HHHHHH)
++Size  85: 51,85   BAD  (HHHHHH)
++Size  86: 52,86   BAD  (HHHHHH)
++Size  87: 52,87   BAD  (HHHHHH)
++Size  88: 53,88   BAD  (HHHHHH)
++Size  89: 54,89   BAD  (HHHHHH)
++Size  90: 54,90   BAD  (HHHHHH)
++Size  91: 55,91   BAD  (HHHHHH)
++Size  92: 55,92   BAD  (HHHHHH)
++Size  93: 56,93   BAD  (HHHHHH)
++Size  94: 57,94   BAD  (HHHHHH)
++Size  95: 57,95   BAD  (HHHHHH)
++Size  96: 58,96   BAD  (HHHHHH)
++Size  97: 58,97   BAD  (HHHHHH)
++Size  98: 59,98   BAD  (HHHHHH)
++Size  99: 60,99   BAD  (HHHHHH)
++Size 100: 60,100  BAD  (HHHHHH)
++
++Windows 8.1
++-----------
++
++Size   1: 1,2     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 2,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 3,5     BAD  (HHHHHH)
++Size   6: 4,6     BAD  (HHHHHH)
++Size   7: 4,7     BAD  (HHHHHH)
++Size   8: 5,8     BAD  (HHHHHH)
++Size   9: 5,9     BAD  (HHHHHH)
++Size  10: 6,10    BAD  (HHHHHH)
++Size  11: 7,11    BAD  (HHHHHH)
++Size  12: 7,12    BAD  (HHHHHH)
++Size  13: 8,13    BAD  (HHHHHH)
++Size  14: 8,14    BAD  (HHHHHH)
++Size  15: 9,15    BAD  (HHHHHH)
++Size  16: 10,16   BAD  (HHHHHH)
++Size  17: 10,17   BAD  (HHHHHH)
++Size  18: 11,18   BAD  (HHHHHH)
++Size  19: 11,19   BAD  (HHHHHH)
++Size  20: 12,20   BAD  (HHHHHH)
++Size  21: 13,21   BAD  (HHHHHH)
++Size  22: 13,22   BAD  (HHHHHH)
++Size  23: 14,23   BAD  (HHHHHH)
++Size  24: 14,24   BAD  (HHHHHH)
++Size  25: 15,25   BAD  (HHHHHH)
++Size  26: 16,26   BAD  (HHHHHH)
++Size  27: 16,27   BAD  (HHHHHH)
++Size  28: 17,28   BAD  (HHHHHH)
++Size  29: 17,29   BAD  (HHHHHH)
++Size  30: 18,30   BAD  (HHHHHH)
++Size  31: 19,31   BAD  (HHHHHH)
++Size  32: 19,32   BAD  (HHHHHH)
++Size  33: 20,33   BAD  (HHHHHH)
++Size  34: 20,34   BAD  (HHHHHH)
++Size  35: 21,35   BAD  (HHHHHH)
++Size  36: 22,36   BAD  (HHHHHH)
++Size  37: 22,37   BAD  (HHHHHH)
++Size  38: 23,38   BAD  (HHHHHH)
++Size  39: 23,39   BAD  (HHHHHH)
++Size  40: 24,40   BAD  (HHHHHH)
++Size  41: 25,41   BAD  (HHHHHH)
++Size  42: 25,42   BAD  (HHHHHH)
++Size  43: 26,43   BAD  (HHHHHH)
++Size  44: 27,44   BAD  (HHHHHH)
++Size  45: 27,45   BAD  (HHHHHH)
++Size  46: 28,46   BAD  (HHHHHH)
++Size  47: 28,47   BAD  (HHHHHH)
++Size  48: 29,48   BAD  (HHHHHH)
++Size  49: 30,49   BAD  (HHHHHH)
++Size  50: 30,50   BAD  (HHHHHH)
++Size  51: 31,51   BAD  (HHHHHH)
++Size  52: 31,52   BAD  (HHHHHH)
++Size  53: 32,53   BAD  (HHHHHH)
++Size  54: 33,54   BAD  (HHHHHH)
++Size  55: 33,55   BAD  (HHHHHH)
++Size  56: 34,56   BAD  (HHHHHH)
++Size  57: 34,57   BAD  (HHHHHH)
++Size  58: 35,58   BAD  (HHHHHH)
++Size  59: 36,59   BAD  (HHHHHH)
++Size  60: 36,60   BAD  (HHHHHH)
++Size  61: 37,61   BAD  (HHHHHH)
++Size  62: 37,62   BAD  (HHHHHH)
++Size  63: 38,63   BAD  (HHHHHH)
++Size  64: 39,65   BAD  (HHHHHH)
++Size  65: 39,65   BAD  (HHHHHH)
++Size  66: 40,66   BAD  (HHHHHH)
++Size  67: 40,67   BAD  (HHHHHH)
++Size  68: 41,68   BAD  (HHHHHH)
++Size  69: 42,69   BAD  (HHHHHH)
++Size  70: 42,70   BAD  (HHHHHH)
++Size  71: 43,71   BAD  (HHHHHH)
++Size  72: 43,72   BAD  (HHHHHH)
++Size  73: 44,73   BAD  (HHHHHH)
++Size  74: 45,74   BAD  (HHHHHH)
++Size  75: 45,75   BAD  (HHHHHH)
++Size  76: 46,76   BAD  (HHHHHH)
++Size  77: 46,77   BAD  (HHHHHH)
++Size  78: 47,78   BAD  (HHHHHH)
++Size  79: 48,79   BAD  (HHHHHH)
++Size  80: 48,80   BAD  (HHHHHH)
++Size  81: 49,81   BAD  (HHHHHH)
++Size  82: 49,82   BAD  (HHHHHH)
++Size  83: 50,83   BAD  (HHHHHH)
++Size  84: 51,84   BAD  (HHHHHH)
++Size  85: 51,85   BAD  (HHHHHH)
++Size  86: 52,86   BAD  (HHHHHH)
++Size  87: 52,87   BAD  (HHHHHH)
++Size  88: 53,88   BAD  (HHHHHH)
++Size  89: 54,89   BAD  (HHHHHH)
++Size  90: 54,90   BAD  (HHHHHH)
++Size  91: 55,91   BAD  (HHHHHH)
++Size  92: 55,92   BAD  (HHHHHH)
++Size  93: 56,93   BAD  (HHHHHH)
++Size  94: 57,94   BAD  (HHHHHH)
++Size  95: 57,95   BAD  (HHHHHH)
++Size  96: 58,96   BAD  (HHHHHH)
++Size  97: 58,97   BAD  (HHHHHH)
++Size  98: 59,98   BAD  (HHHHHH)
++Size  99: 60,99   BAD  (HHHHHH)
++Size 100: 60,100  BAD  (HHHHHH)
++
++Windows 10 14342 Old Console
++----------------------------
++
++Size   1: 1,2     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 2,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 3,5     BAD  (HHHHHH)
++Size   6: 4,6     BAD  (HHHHHH)
++Size   7: 4,7     BAD  (HHHHHH)
++Size   8: 5,8     BAD  (HHHHHH)
++Size   9: 5,9     BAD  (HHHHHH)
++Size  10: 6,10    BAD  (HHHHHH)
++Size  11: 7,11    BAD  (HHHHHH)
++Size  12: 7,12    BAD  (HHHHHH)
++Size  13: 8,13    BAD  (HHHHHH)
++Size  14: 8,14    BAD  (HHHHHH)
++Size  15: 9,15    BAD  (HHHHHH)
++Size  16: 10,16   BAD  (HHHHHH)
++Size  17: 10,17   BAD  (HHHHHH)
++Size  18: 11,18   BAD  (HHHHHH)
++Size  19: 11,19   BAD  (HHHHHH)
++Size  20: 12,20   BAD  (HHHHHH)
++Size  21: 13,21   BAD  (HHHHHH)
++Size  22: 13,22   BAD  (HHHHHH)
++Size  23: 14,23   BAD  (HHHHHH)
++Size  24: 14,24   BAD  (HHHHHH)
++Size  25: 15,25   BAD  (HHHHHH)
++Size  26: 16,26   BAD  (HHHHHH)
++Size  27: 16,27   BAD  (HHHHHH)
++Size  28: 17,28   BAD  (HHHHHH)
++Size  29: 17,29   BAD  (HHHHHH)
++Size  30: 18,30   BAD  (HHHHHH)
++Size  31: 19,31   BAD  (HHHHHH)
++Size  32: 19,32   BAD  (HHHHHH)
++Size  33: 20,33   BAD  (HHHHHH)
++Size  34: 20,34   BAD  (HHHHHH)
++Size  35: 21,35   BAD  (HHHHHH)
++Size  36: 22,36   BAD  (HHHHHH)
++Size  37: 22,37   BAD  (HHHHHH)
++Size  38: 23,38   BAD  (HHHHHH)
++Size  39: 23,39   BAD  (HHHHHH)
++Size  40: 24,40   BAD  (HHHHHH)
++Size  41: 25,41   BAD  (HHHHHH)
++Size  42: 25,42   BAD  (HHHHHH)
++Size  43: 26,43   BAD  (HHHHHH)
++Size  44: 27,44   BAD  (HHHHHH)
++Size  45: 27,45   BAD  (HHHHHH)
++Size  46: 28,46   BAD  (HHHHHH)
++Size  47: 28,47   BAD  (HHHHHH)
++Size  48: 29,48   BAD  (HHHHHH)
++Size  49: 30,49   BAD  (HHHHHH)
++Size  50: 30,50   BAD  (HHHHHH)
++Size  51: 31,51   BAD  (HHHHHH)
++Size  52: 31,52   BAD  (HHHHHH)
++Size  53: 32,53   BAD  (HHHHHH)
++Size  54: 33,54   BAD  (HHHHHH)
++Size  55: 33,55   BAD  (HHHHHH)
++Size  56: 34,56   BAD  (HHHHHH)
++Size  57: 34,57   BAD  (HHHHHH)
++Size  58: 35,58   BAD  (HHHHHH)
++Size  59: 36,59   BAD  (HHHHHH)
++Size  60: 36,60   BAD  (HHHHHH)
++Size  61: 37,61   BAD  (HHHHHH)
++Size  62: 37,62   BAD  (HHHHHH)
++Size  63: 38,63   BAD  (HHHHHH)
++Size  64: 39,65   BAD  (HHHHHH)
++Size  65: 39,65   BAD  (HHHHHH)
++Size  66: 40,66   BAD  (HHHHHH)
++Size  67: 40,67   BAD  (HHHHHH)
++Size  68: 41,68   BAD  (HHHHHH)
++Size  69: 42,69   BAD  (HHHHHH)
++Size  70: 42,70   BAD  (HHHHHH)
++Size  71: 43,71   BAD  (HHHHHH)
++Size  72: 43,72   BAD  (HHHHHH)
++Size  73: 44,73   BAD  (HHHHHH)
++Size  74: 45,74   BAD  (HHHHHH)
++Size  75: 45,75   BAD  (HHHHHH)
++Size  76: 46,76   BAD  (HHHHHH)
++Size  77: 46,77   BAD  (HHHHHH)
++Size  78: 47,78   BAD  (HHHHHH)
++Size  79: 48,79   BAD  (HHHHHH)
++Size  80: 48,80   BAD  (HHHHHH)
++Size  81: 49,81   BAD  (HHHHHH)
++Size  82: 49,82   BAD  (HHHHHH)
++Size  83: 50,83   BAD  (HHHHHH)
++Size  84: 51,84   BAD  (HHHHHH)
++Size  85: 51,85   BAD  (HHHHHH)
++Size  86: 52,86   BAD  (HHHHHH)
++Size  87: 52,87   BAD  (HHHHHH)
++Size  88: 53,88   BAD  (HHHHHH)
++Size  89: 54,89   BAD  (HHHHHH)
++Size  90: 54,90   BAD  (HHHHHH)
++Size  91: 55,91   BAD  (HHHHHH)
++Size  92: 55,92   BAD  (HHHHHH)
++Size  93: 56,93   BAD  (HHHHHH)
++Size  94: 57,94   BAD  (HHHHHH)
++Size  95: 57,95   BAD  (HHHHHH)
++Size  96: 58,96   BAD  (HHHHHH)
++Size  97: 58,97   BAD  (HHHHHH)
++Size  98: 59,98   BAD  (HHHHHH)
++Size  99: 60,99   BAD  (HHHHHH)
++Size 100: 60,100  BAD  (HHHHHH)
++
++Windows 10 14342 New Console
++----------------------------
++
++Size   1: 1,1     BAD  (HHHHHH)
++Size   2: 1,2     BAD  (HHHHHH)
++Size   3: 2,3     BAD  (HHHHHH)
++Size   4: 2,4     BAD  (HHHHHH)
++Size   5: 3,5     BAD  (HHHHHH)
++Size   6: 4,6     BAD  (HHHHHH)
++Size   7: 4,7     BAD  (HHHHHH)
++Size   8: 5,8     BAD  (HHHHHH)
++Size   9: 5,9     BAD  (HHHHHH)
++Size  10: 6,10    BAD  (HHHHHH)
++Size  11: 7,11    BAD  (HHHHHH)
++Size  12: 7,12    BAD  (HHHHHH)
++Size  13: 8,13    BAD  (HHHHHH)
++Size  14: 8,14    BAD  (HHHHHH)
++Size  15: 9,15    BAD  (HHHHHH)
++Size  16: 10,16   BAD  (HHHHHH)
++Size  17: 10,17   BAD  (HHHHHH)
++Size  18: 11,18   BAD  (HHHHHH)
++Size  19: 11,19   BAD  (HHHHHH)
++Size  20: 12,20   BAD  (HHHHHH)
++Size  21: 13,21   BAD  (HHHHHH)
++Size  22: 13,22   BAD  (HHHHHH)
++Size  23: 14,23   BAD  (HHHHHH)
++Size  24: 14,24   BAD  (HHHHHH)
++Size  25: 15,25   BAD  (HHHHHH)
++Size  26: 16,26   BAD  (HHHHHH)
++Size  27: 16,27   BAD  (HHHHHH)
++Size  28: 17,28   BAD  (HHHHHH)
++Size  29: 17,29   BAD  (HHHHHH)
++Size  30: 18,30   BAD  (HHHHHH)
++Size  31: 19,31   BAD  (HHHHHH)
++Size  32: 19,32   BAD  (HHHHHH)
++Size  33: 20,33   BAD  (HHHHHH)
++Size  34: 20,34   BAD  (HHHHHH)
++Size  35: 21,35   BAD  (HHHHHH)
++Size  36: 22,36   BAD  (HHHHHH)
++Size  37: 22,37   BAD  (HHHHHH)
++Size  38: 23,38   BAD  (HHHHHH)
++Size  39: 23,39   BAD  (HHHHHH)
++Size  40: 24,40   BAD  (HHHHHH)
++Size  41: 25,41   BAD  (HHHHHH)
++Size  42: 25,42   BAD  (HHHHHH)
++Size  43: 26,43   BAD  (HHHHHH)
++Size  44: 27,44   BAD  (HHHHHH)
++Size  45: 27,45   BAD  (HHHHHH)
++Size  46: 28,46   BAD  (HHHHHH)
++Size  47: 28,47   BAD  (HHHHHH)
++Size  48: 29,48   BAD  (HHHHHH)
++Size  49: 30,49   BAD  (HHHHHH)
++Size  50: 30,50   BAD  (HHHHHH)
++Size  51: 31,51   BAD  (HHHHHH)
++Size  52: 31,52   BAD  (HHHHHH)
++Size  53: 32,53   BAD  (HHHHHH)
++Size  54: 33,54   BAD  (HHHHHH)
++Size  55: 33,55   BAD  (HHHHHH)
++Size  56: 34,56   BAD  (HHHHHH)
++Size  57: 34,57   BAD  (HHHHHH)
++Size  58: 35,58   BAD  (HHHHHH)
++Size  59: 36,59   BAD  (HHHHHH)
++Size  60: 36,60   BAD  (HHHHHH)
++Size  61: 37,61   BAD  (HHHHHH)
++Size  62: 37,62   BAD  (HHHHHH)
++Size  63: 38,63   BAD  (HHHHHH)
++Size  64: 39,64   BAD  (HHHHHH)
++Size  65: 39,65   BAD  (HHHHHH)
++Size  66: 40,66   BAD  (HHHHHH)
++Size  67: 40,67   BAD  (HHHHHH)
++Size  68: 41,68   BAD  (HHHHHH)
++Size  69: 42,69   BAD  (HHHHHH)
++Size  70: 42,70   BAD  (HHHHHH)
++Size  71: 43,71   BAD  (HHHHHH)
++Size  72: 43,72   BAD  (HHHHHH)
++Size  73: 44,73   BAD  (HHHHHH)
++Size  74: 45,74   BAD  (HHHHHH)
++Size  75: 45,75   BAD  (HHHHHH)
++Size  76: 46,76   BAD  (HHHHHH)
++Size  77: 46,77   BAD  (HHHHHH)
++Size  78: 47,78   BAD  (HHHHHH)
++Size  79: 48,79   BAD  (HHHHHH)
++Size  80: 48,80   BAD  (HHHHHH)
++Size  81: 49,81   BAD  (HHHHHH)
++Size  82: 49,82   BAD  (HHHHHH)
++Size  83: 50,83   BAD  (HHHHHH)
++Size  84: 51,84   BAD  (HHHHHH)
++Size  85: 51,85   BAD  (HHHHHH)
++Size  86: 52,86   BAD  (HHHHHH)
++Size  87: 52,87   BAD  (HHHHHH)
++Size  88: 53,88   BAD  (HHHHHH)
++Size  89: 54,89   BAD  (HHHHHH)
++Size  90: 54,90   BAD  (HHHHHH)
++Size  91: 55,91   BAD  (HHHHHH)
++Size  92: 55,92   BAD  (HHHHHH)
++Size  93: 56,93   BAD  (HHHHHH)
++Size  94: 57,94   BAD  (HHHHHH)
++Size  95: 57,95   BAD  (HHHHHH)
++Size  96: 58,96   BAD  (HHHHHH)
++Size  97: 58,97   BAD  (HHHHHH)
++Size  98: 59,98   BAD  (HHHHHH)
++Size  99: 60,99   BAD  (HHHHHH)
++Size 100: 60,100  BAD  (HHHHHH)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ed3637eac1f89ccd4035bf45e58290821f1827b4
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,630 @@@
++=======================================
++Code Page 932, Japanese, MS Gothic font
++=======================================
++
++Options: -face-gothic -family 0x36
++Chars: A2 A3 2014 3044 30FC 4000
++
++Vista
++-----
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,4     OK   (HHHFFF)
++Size   5: 3,5     OK   (HHHFFF)
++Size   6: 3,6     OK   (HHHFFF)
++Size   7: 4,7     OK   (HHHFFF)
++Size   8: 4,8     OK   (HHHFFF)
++Size   9: 5,9     OK   (HHHFFF)
++Size  10: 5,10    OK   (HHHFFF)
++Size  11: 6,11    OK   (HHHFFF)
++Size  12: 6,12    OK   (HHHFFF)
++Size  13: 7,13    OK   (HHHFFF)
++Size  14: 7,14    BAD  (HHHFHH)
++Size  15: 8,15    OK   (HHHFFF)
++Size  16: 8,16    BAD  (HHHFHH)
++Size  17: 9,17    OK   (HHHFFF)
++Size  18: 9,18    BAD  (HHHFHH)
++Size  19: 10,19   OK   (HHHFFF)
++Size  20: 10,20   BAD  (HHHFHH)
++Size  21: 11,21   OK   (HHHFFF)
++Size  22: 11,22   BAD  (HHHFHH)
++Size  23: 12,23   BAD  (HHHFHH)
++Size  24: 12,24   BAD  (HHHFHH)
++Size  25: 13,25   BAD  (HHHFHH)
++Size  26: 13,26   BAD  (HHHFHH)
++Size  27: 14,27   BAD  (HHHFHH)
++Size  28: 14,28   BAD  (HHHFHH)
++Size  29: 15,29   BAD  (HHHFHH)
++Size  30: 15,30   BAD  (HHHFHH)
++Size  31: 16,31   BAD  (HHHFHH)
++Size  32: 16,33   BAD  (HHHFHH)
++Size  33: 17,33   BAD  (HHHFHH)
++Size  34: 17,34   BAD  (HHHFHH)
++Size  35: 18,35   BAD  (HHHFHH)
++Size  36: 18,36   BAD  (HHHFHH)
++Size  37: 19,37   BAD  (HHHFHH)
++Size  38: 19,38   BAD  (HHHFHH)
++Size  39: 20,39   BAD  (HHHFHH)
++Size  40: 20,40   BAD  (HHHFHH)
++Size  41: 21,41   BAD  (HHHFHH)
++Size  42: 21,42   BAD  (HHHFHH)
++Size  43: 22,43   BAD  (HHHFHH)
++Size  44: 22,44   BAD  (HHHFHH)
++Size  45: 23,45   BAD  (HHHFHH)
++Size  46: 23,46   BAD  (HHHFHH)
++Size  47: 24,47   BAD  (HHHFHH)
++Size  48: 24,48   BAD  (HHHFHH)
++Size  49: 25,49   BAD  (HHHFHH)
++Size  50: 25,50   BAD  (HHHFHH)
++Size  51: 26,51   BAD  (HHHFHH)
++Size  52: 26,52   BAD  (HHHFHH)
++Size  53: 27,53   BAD  (HHHFHH)
++Size  54: 27,54   BAD  (HHHFHH)
++Size  55: 28,55   BAD  (HHHFHH)
++Size  56: 28,56   BAD  (HHHFHH)
++Size  57: 29,57   BAD  (HHHFHH)
++Size  58: 29,58   BAD  (HHHFHH)
++Size  59: 30,59   BAD  (HHHFHH)
++Size  60: 30,60   BAD  (HHHFHH)
++Size  61: 31,61   BAD  (HHHFHH)
++Size  62: 31,62   BAD  (HHHFHH)
++Size  63: 32,63   BAD  (HHHFHH)
++Size  64: 32,64   BAD  (HHHFHH)
++Size  65: 33,65   BAD  (HHHFHH)
++Size  66: 33,66   BAD  (HHHFHH)
++Size  67: 34,67   BAD  (HHHFHH)
++Size  68: 34,68   BAD  (HHHFHH)
++Size  69: 35,69   BAD  (HHHFHH)
++Size  70: 35,70   BAD  (HHHFHH)
++Size  71: 36,71   BAD  (HHHFHH)
++Size  72: 36,72   BAD  (HHHFHH)
++Size  73: 37,73   BAD  (HHHFHH)
++Size  74: 37,74   BAD  (HHHFHH)
++Size  75: 38,75   BAD  (HHHFHH)
++Size  76: 38,76   BAD  (HHHFHH)
++Size  77: 39,77   BAD  (HHHFHH)
++Size  78: 39,78   BAD  (HHHFHH)
++Size  79: 40,79   BAD  (HHHFHH)
++Size  80: 40,80   BAD  (HHHFHH)
++Size  81: 41,81   BAD  (HHHFHH)
++Size  82: 41,82   BAD  (HHHFHH)
++Size  83: 42,83   BAD  (HHHFHH)
++Size  84: 42,84   BAD  (HHHFHH)
++Size  85: 43,85   BAD  (HHHFHH)
++Size  86: 43,86   BAD  (HHHFHH)
++Size  87: 44,87   BAD  (HHHFHH)
++Size  88: 44,88   BAD  (HHHFHH)
++Size  89: 45,89   BAD  (HHHFHH)
++Size  90: 45,90   BAD  (HHHFHH)
++Size  91: 46,91   BAD  (HHHFHH)
++Size  92: 46,92   BAD  (HHHFHH)
++Size  93: 47,93   BAD  (HHHFHH)
++Size  94: 47,94   BAD  (HHHFHH)
++Size  95: 48,95   BAD  (HHHFHH)
++Size  96: 48,97   BAD  (HHHFHH)
++Size  97: 49,97   BAD  (HHHFHH)
++Size  98: 49,98   BAD  (HHHFHH)
++Size  99: 50,99   BAD  (HHHFHH)
++Size 100: 50,100  BAD  (HHHFHH)
++
++Windows 7
++---------
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,4     OK   (HHHFFF)
++Size   5: 3,5     OK   (HHHFFF)
++Size   6: 3,6     OK   (HHHFFF)
++Size   7: 4,7     OK   (HHHFFF)
++Size   8: 4,8     OK   (HHHFFF)
++Size   9: 5,9     OK   (HHHFFF)
++Size  10: 5,10    OK   (HHHFFF)
++Size  11: 6,11    OK   (HHHFFF)
++Size  12: 6,12    OK   (HHHFFF)
++Size  13: 7,13    OK   (HHHFFF)
++Size  14: 7,14    BAD  (FFFFFF)
++Size  15: 8,15    OK   (HHHFFF)
++Size  16: 8,16    BAD  (FFFFFF)
++Size  17: 9,17    OK   (HHHFFF)
++Size  18: 9,18    BAD  (FFFFFF)
++Size  19: 10,19   OK   (HHHFFF)
++Size  20: 10,20   BAD  (FFFFFF)
++Size  21: 11,21   OK   (HHHFFF)
++Size  22: 11,22   BAD  (FFFFFF)
++Size  23: 12,23   BAD  (FFFFFF)
++Size  24: 12,24   BAD  (FFFFFF)
++Size  25: 13,25   BAD  (FFFFFF)
++Size  26: 13,26   BAD  (FFFFFF)
++Size  27: 14,27   BAD  (FFFFFF)
++Size  28: 14,28   BAD  (FFFFFF)
++Size  29: 15,29   BAD  (FFFFFF)
++Size  30: 15,30   BAD  (FFFFFF)
++Size  31: 16,31   BAD  (FFFFFF)
++Size  32: 16,33   BAD  (FFFFFF)
++Size  33: 17,33   BAD  (FFFFFF)
++Size  34: 17,34   BAD  (FFFFFF)
++Size  35: 18,35   BAD  (FFFFFF)
++Size  36: 18,36   BAD  (FFFFFF)
++Size  37: 19,37   BAD  (FFFFFF)
++Size  38: 19,38   BAD  (FFFFFF)
++Size  39: 20,39   BAD  (FFFFFF)
++Size  40: 20,40   BAD  (FFFFFF)
++Size  41: 21,41   BAD  (FFFFFF)
++Size  42: 21,42   BAD  (FFFFFF)
++Size  43: 22,43   BAD  (FFFFFF)
++Size  44: 22,44   BAD  (FFFFFF)
++Size  45: 23,45   BAD  (FFFFFF)
++Size  46: 23,46   BAD  (FFFFFF)
++Size  47: 24,47   BAD  (FFFFFF)
++Size  48: 24,48   BAD  (FFFFFF)
++Size  49: 25,49   BAD  (FFFFFF)
++Size  50: 25,50   BAD  (FFFFFF)
++Size  51: 26,51   BAD  (FFFFFF)
++Size  52: 26,52   BAD  (FFFFFF)
++Size  53: 27,53   BAD  (FFFFFF)
++Size  54: 27,54   BAD  (FFFFFF)
++Size  55: 28,55   BAD  (FFFFFF)
++Size  56: 28,56   BAD  (FFFFFF)
++Size  57: 29,57   BAD  (FFFFFF)
++Size  58: 29,58   BAD  (FFFFFF)
++Size  59: 30,59   BAD  (FFFFFF)
++Size  60: 30,60   BAD  (FFFFFF)
++Size  61: 31,61   BAD  (FFFFFF)
++Size  62: 31,62   BAD  (FFFFFF)
++Size  63: 32,63   BAD  (FFFFFF)
++Size  64: 32,64   BAD  (FFFFFF)
++Size  65: 33,65   BAD  (FFFFFF)
++Size  66: 33,66   BAD  (FFFFFF)
++Size  67: 34,67   BAD  (FFFFFF)
++Size  68: 34,68   BAD  (FFFFFF)
++Size  69: 35,69   BAD  (FFFFFF)
++Size  70: 35,70   BAD  (FFFFFF)
++Size  71: 36,71   BAD  (FFFFFF)
++Size  72: 36,72   BAD  (FFFFFF)
++Size  73: 37,73   BAD  (FFFFFF)
++Size  74: 37,74   BAD  (FFFFFF)
++Size  75: 38,75   BAD  (FFFFFF)
++Size  76: 38,76   BAD  (FFFFFF)
++Size  77: 39,77   BAD  (FFFFFF)
++Size  78: 39,78   BAD  (FFFFFF)
++Size  79: 40,79   BAD  (FFFFFF)
++Size  80: 40,80   BAD  (FFFFFF)
++Size  81: 41,81   BAD  (FFFFFF)
++Size  82: 41,82   BAD  (FFFFFF)
++Size  83: 42,83   BAD  (FFFFFF)
++Size  84: 42,84   BAD  (FFFFFF)
++Size  85: 43,85   BAD  (FFFFFF)
++Size  86: 43,86   BAD  (FFFFFF)
++Size  87: 44,87   BAD  (FFFFFF)
++Size  88: 44,88   BAD  (FFFFFF)
++Size  89: 45,89   BAD  (FFFFFF)
++Size  90: 45,90   BAD  (FFFFFF)
++Size  91: 46,91   BAD  (FFFFFF)
++Size  92: 46,92   BAD  (FFFFFF)
++Size  93: 47,93   BAD  (FFFFFF)
++Size  94: 47,94   BAD  (FFFFFF)
++Size  95: 48,95   BAD  (FFFFFF)
++Size  96: 48,97   BAD  (FFFFFF)
++Size  97: 49,97   BAD  (FFFFFF)
++Size  98: 49,98   BAD  (FFFFFF)
++Size  99: 50,99   BAD  (FFFFFF)
++Size 100: 50,100  BAD  (FFFFFF)
++
++Windows 8
++---------
++
++Size   1: 1,2     BAD  (FFFFHH)
++Size   2: 1,2     BAD  (FFFFHH)
++Size   3: 2,3     BAD  (FFFFFF)
++Size   4: 2,4     BAD  (FFFFHH)
++Size   5: 3,5     BAD  (FFFFFF)
++Size   6: 3,6     BAD  (FFFFHH)
++Size   7: 4,7     BAD  (FFFFFF)
++Size   8: 4,8     BAD  (FFFFHH)
++Size   9: 5,9     BAD  (FFFFFF)
++Size  10: 5,10    BAD  (FFFFHH)
++Size  11: 6,11    BAD  (FFFFFF)
++Size  12: 6,12    BAD  (FFFFHH)
++Size  13: 7,13    BAD  (FFFFFF)
++Size  14: 7,14    BAD  (FFFFHH)
++Size  15: 8,15    BAD  (FFFFFF)
++Size  16: 8,16    BAD  (FFFFHH)
++Size  17: 9,17    BAD  (FFFFFF)
++Size  18: 9,18    BAD  (FFFFHH)
++Size  19: 10,19   BAD  (FFFFFF)
++Size  20: 10,20   BAD  (FFFFFF)
++Size  21: 11,21   BAD  (FFFFFF)
++Size  22: 11,22   BAD  (FFFFFF)
++Size  23: 12,23   BAD  (FFFFFF)
++Size  24: 12,24   BAD  (FFFFFF)
++Size  25: 13,25   BAD  (FFFFFF)
++Size  26: 13,26   BAD  (FFFFFF)
++Size  27: 14,27   BAD  (FFFFFF)
++Size  28: 14,28   BAD  (FFFFFF)
++Size  29: 15,29   BAD  (FFFFFF)
++Size  30: 15,30   BAD  (FFFFFF)
++Size  31: 16,31   BAD  (FFFFFF)
++Size  32: 16,33   BAD  (FFFFFF)
++Size  33: 17,33   BAD  (FFFFFF)
++Size  34: 17,34   BAD  (FFFFFF)
++Size  35: 18,35   BAD  (FFFFFF)
++Size  36: 18,36   BAD  (FFFFFF)
++Size  37: 19,37   BAD  (FFFFFF)
++Size  38: 19,38   BAD  (FFFFFF)
++Size  39: 20,39   BAD  (FFFFFF)
++Size  40: 20,40   BAD  (FFFFFF)
++Size  41: 21,41   BAD  (FFFFFF)
++Size  42: 21,42   BAD  (FFFFFF)
++Size  43: 22,43   BAD  (FFFFFF)
++Size  44: 22,44   BAD  (FFFFFF)
++Size  45: 23,45   BAD  (FFFFFF)
++Size  46: 23,46   BAD  (FFFFFF)
++Size  47: 24,47   BAD  (FFFFFF)
++Size  48: 24,48   BAD  (FFFFFF)
++Size  49: 25,49   BAD  (FFFFFF)
++Size  50: 25,50   BAD  (FFFFFF)
++Size  51: 26,51   BAD  (FFFFFF)
++Size  52: 26,52   BAD  (FFFFFF)
++Size  53: 27,53   BAD  (FFFFFF)
++Size  54: 27,54   BAD  (FFFFFF)
++Size  55: 28,55   BAD  (FFFFFF)
++Size  56: 28,56   BAD  (FFFFFF)
++Size  57: 29,57   BAD  (FFFFFF)
++Size  58: 29,58   BAD  (FFFFFF)
++Size  59: 30,59   BAD  (FFFFFF)
++Size  60: 30,60   BAD  (FFFFFF)
++Size  61: 31,61   BAD  (FFFFFF)
++Size  62: 31,62   BAD  (FFFFFF)
++Size  63: 32,63   BAD  (FFFFFF)
++Size  64: 32,64   BAD  (FFFFFF)
++Size  65: 33,65   BAD  (FFFFFF)
++Size  66: 33,66   BAD  (FFFFFF)
++Size  67: 34,67   BAD  (FFFFFF)
++Size  68: 34,68   BAD  (FFFFFF)
++Size  69: 35,69   BAD  (FFFFFF)
++Size  70: 35,70   BAD  (FFFFFF)
++Size  71: 36,71   BAD  (FFFFFF)
++Size  72: 36,72   BAD  (FFFFFF)
++Size  73: 37,73   BAD  (FFFFFF)
++Size  74: 37,74   BAD  (FFFFFF)
++Size  75: 38,75   BAD  (FFFFFF)
++Size  76: 38,76   BAD  (FFFFFF)
++Size  77: 39,77   BAD  (FFFFFF)
++Size  78: 39,78   BAD  (FFFFFF)
++Size  79: 40,79   BAD  (FFFFFF)
++Size  80: 40,80   BAD  (FFFFFF)
++Size  81: 41,81   BAD  (FFFFFF)
++Size  82: 41,82   BAD  (FFFFFF)
++Size  83: 42,83   BAD  (FFFFFF)
++Size  84: 42,84   BAD  (FFFFFF)
++Size  85: 43,85   BAD  (FFFFFF)
++Size  86: 43,86   BAD  (FFFFFF)
++Size  87: 44,87   BAD  (FFFFFF)
++Size  88: 44,88   BAD  (FFFFFF)
++Size  89: 45,89   BAD  (FFFFFF)
++Size  90: 45,90   BAD  (FFFFFF)
++Size  91: 46,91   BAD  (FFFFFF)
++Size  92: 46,92   BAD  (FFFFFF)
++Size  93: 47,93   BAD  (FFFFFF)
++Size  94: 47,94   BAD  (FFFFFF)
++Size  95: 48,95   BAD  (FFFFFF)
++Size  96: 48,97   BAD  (FFFFFF)
++Size  97: 49,97   BAD  (FFFFFF)
++Size  98: 49,98   BAD  (FFFFFF)
++Size  99: 50,99   BAD  (FFFFFF)
++Size 100: 50,100  BAD  (FFFFFF)
++
++Windows 8.1
++-----------
++
++Size   1: 1,2     BAD  (FFFFHH)
++Size   2: 1,2     BAD  (FFFFHH)
++Size   3: 2,3     BAD  (FFFFFF)
++Size   4: 2,4     BAD  (FFFFHH)
++Size   5: 3,5     BAD  (FFFFFF)
++Size   6: 3,6     BAD  (FFFFHH)
++Size   7: 4,7     BAD  (FFFFFF)
++Size   8: 4,8     BAD  (FFFFHH)
++Size   9: 5,9     BAD  (FFFFFF)
++Size  10: 5,10    BAD  (FFFFHH)
++Size  11: 6,11    BAD  (FFFFFF)
++Size  12: 6,12    BAD  (FFFFHH)
++Size  13: 7,13    BAD  (FFFFFF)
++Size  14: 7,14    BAD  (FFFFHH)
++Size  15: 8,15    BAD  (FFFFFF)
++Size  16: 8,16    BAD  (FFFFHH)
++Size  17: 9,17    BAD  (FFFFFF)
++Size  18: 9,18    BAD  (FFFFHH)
++Size  19: 10,19   BAD  (FFFFFF)
++Size  20: 10,20   BAD  (FFFFFF)
++Size  21: 11,21   BAD  (FFFFFF)
++Size  22: 11,22   BAD  (FFFFFF)
++Size  23: 12,23   BAD  (FFFFFF)
++Size  24: 12,24   BAD  (FFFFFF)
++Size  25: 13,25   BAD  (FFFFFF)
++Size  26: 13,26   BAD  (FFFFFF)
++Size  27: 14,27   BAD  (FFFFFF)
++Size  28: 14,28   BAD  (FFFFFF)
++Size  29: 15,29   BAD  (FFFFFF)
++Size  30: 15,30   BAD  (FFFFFF)
++Size  31: 16,31   BAD  (FFFFFF)
++Size  32: 16,33   BAD  (FFFFFF)
++Size  33: 17,33   BAD  (FFFFFF)
++Size  34: 17,34   BAD  (FFFFFF)
++Size  35: 18,35   BAD  (FFFFFF)
++Size  36: 18,36   BAD  (FFFFFF)
++Size  37: 19,37   BAD  (FFFFFF)
++Size  38: 19,38   BAD  (FFFFFF)
++Size  39: 20,39   BAD  (FFFFFF)
++Size  40: 20,40   BAD  (FFFFFF)
++Size  41: 21,41   BAD  (FFFFFF)
++Size  42: 21,42   BAD  (FFFFFF)
++Size  43: 22,43   BAD  (FFFFFF)
++Size  44: 22,44   BAD  (FFFFFF)
++Size  45: 23,45   BAD  (FFFFFF)
++Size  46: 23,46   BAD  (FFFFFF)
++Size  47: 24,47   BAD  (FFFFFF)
++Size  48: 24,48   BAD  (FFFFFF)
++Size  49: 25,49   BAD  (FFFFFF)
++Size  50: 25,50   BAD  (FFFFFF)
++Size  51: 26,51   BAD  (FFFFFF)
++Size  52: 26,52   BAD  (FFFFFF)
++Size  53: 27,53   BAD  (FFFFFF)
++Size  54: 27,54   BAD  (FFFFFF)
++Size  55: 28,55   BAD  (FFFFFF)
++Size  56: 28,56   BAD  (FFFFFF)
++Size  57: 29,57   BAD  (FFFFFF)
++Size  58: 29,58   BAD  (FFFFFF)
++Size  59: 30,59   BAD  (FFFFFF)
++Size  60: 30,60   BAD  (FFFFFF)
++Size  61: 31,61   BAD  (FFFFFF)
++Size  62: 31,62   BAD  (FFFFFF)
++Size  63: 32,63   BAD  (FFFFFF)
++Size  64: 32,64   BAD  (FFFFFF)
++Size  65: 33,65   BAD  (FFFFFF)
++Size  66: 33,66   BAD  (FFFFFF)
++Size  67: 34,67   BAD  (FFFFFF)
++Size  68: 34,68   BAD  (FFFFFF)
++Size  69: 35,69   BAD  (FFFFFF)
++Size  70: 35,70   BAD  (FFFFFF)
++Size  71: 36,71   BAD  (FFFFFF)
++Size  72: 36,72   BAD  (FFFFFF)
++Size  73: 37,73   BAD  (FFFFFF)
++Size  74: 37,74   BAD  (FFFFFF)
++Size  75: 38,75   BAD  (FFFFFF)
++Size  76: 38,76   BAD  (FFFFFF)
++Size  77: 39,77   BAD  (FFFFFF)
++Size  78: 39,78   BAD  (FFFFFF)
++Size  79: 40,79   BAD  (FFFFFF)
++Size  80: 40,80   BAD  (FFFFFF)
++Size  81: 41,81   BAD  (FFFFFF)
++Size  82: 41,82   BAD  (FFFFFF)
++Size  83: 42,83   BAD  (FFFFFF)
++Size  84: 42,84   BAD  (FFFFFF)
++Size  85: 43,85   BAD  (FFFFFF)
++Size  86: 43,86   BAD  (FFFFFF)
++Size  87: 44,87   BAD  (FFFFFF)
++Size  88: 44,88   BAD  (FFFFFF)
++Size  89: 45,89   BAD  (FFFFFF)
++Size  90: 45,90   BAD  (FFFFFF)
++Size  91: 46,91   BAD  (FFFFFF)
++Size  92: 46,92   BAD  (FFFFFF)
++Size  93: 47,93   BAD  (FFFFFF)
++Size  94: 47,94   BAD  (FFFFFF)
++Size  95: 48,95   BAD  (FFFFFF)
++Size  96: 48,97   BAD  (FFFFFF)
++Size  97: 49,97   BAD  (FFFFFF)
++Size  98: 49,98   BAD  (FFFFFF)
++Size  99: 50,99   BAD  (FFFFFF)
++Size 100: 50,100  BAD  (FFFFFF)
++
++Windows 10 14342 Old Console
++----------------------------
++
++Size   1: 1,2     BAD  (FFFFHH)
++Size   2: 1,2     BAD  (FFFFHH)
++Size   3: 2,3     BAD  (FFFFFF)
++Size   4: 2,4     BAD  (FFFFHH)
++Size   5: 3,5     BAD  (FFFFFF)
++Size   6: 3,6     BAD  (FFFFHH)
++Size   7: 4,7     BAD  (FFFFFF)
++Size   8: 4,8     BAD  (FFFFHH)
++Size   9: 5,9     BAD  (FFFFFF)
++Size  10: 5,10    BAD  (FFFFHH)
++Size  11: 6,11    BAD  (FFFFFF)
++Size  12: 6,12    BAD  (FFFFHH)
++Size  13: 7,13    BAD  (FFFFFF)
++Size  14: 7,14    BAD  (FFFFHH)
++Size  15: 8,15    BAD  (FFFFFF)
++Size  16: 8,16    BAD  (FFFFHH)
++Size  17: 9,17    BAD  (FFFFFF)
++Size  18: 9,18    BAD  (FFFFHH)
++Size  19: 10,19   BAD  (FFFFFF)
++Size  20: 10,20   BAD  (FFFFFF)
++Size  21: 11,21   BAD  (FFFFFF)
++Size  22: 11,22   BAD  (FFFFFF)
++Size  23: 12,23   BAD  (FFFFFF)
++Size  24: 12,24   BAD  (FFFFFF)
++Size  25: 13,25   BAD  (FFFFFF)
++Size  26: 13,26   BAD  (FFFFFF)
++Size  27: 14,27   BAD  (FFFFFF)
++Size  28: 14,28   BAD  (FFFFFF)
++Size  29: 15,29   BAD  (FFFFFF)
++Size  30: 15,30   BAD  (FFFFFF)
++Size  31: 16,31   BAD  (FFFFFF)
++Size  32: 16,33   BAD  (FFFFFF)
++Size  33: 17,33   BAD  (FFFFFF)
++Size  34: 17,34   BAD  (FFFFFF)
++Size  35: 18,35   BAD  (FFFFFF)
++Size  36: 18,36   BAD  (FFFFFF)
++Size  37: 19,37   BAD  (FFFFFF)
++Size  38: 19,38   BAD  (FFFFFF)
++Size  39: 20,39   BAD  (FFFFFF)
++Size  40: 20,40   BAD  (FFFFFF)
++Size  41: 21,41   BAD  (FFFFFF)
++Size  42: 21,42   BAD  (FFFFFF)
++Size  43: 22,43   BAD  (FFFFFF)
++Size  44: 22,44   BAD  (FFFFFF)
++Size  45: 23,45   BAD  (FFFFFF)
++Size  46: 23,46   BAD  (FFFFFF)
++Size  47: 24,47   BAD  (FFFFFF)
++Size  48: 24,48   BAD  (FFFFFF)
++Size  49: 25,49   BAD  (FFFFFF)
++Size  50: 25,50   BAD  (FFFFFF)
++Size  51: 26,51   BAD  (FFFFFF)
++Size  52: 26,52   BAD  (FFFFFF)
++Size  53: 27,53   BAD  (FFFFFF)
++Size  54: 27,54   BAD  (FFFFFF)
++Size  55: 28,55   BAD  (FFFFFF)
++Size  56: 28,56   BAD  (FFFFFF)
++Size  57: 29,57   BAD  (FFFFFF)
++Size  58: 29,58   BAD  (FFFFFF)
++Size  59: 30,59   BAD  (FFFFFF)
++Size  60: 30,60   BAD  (FFFFFF)
++Size  61: 31,61   BAD  (FFFFFF)
++Size  62: 31,62   BAD  (FFFFFF)
++Size  63: 32,63   BAD  (FFFFFF)
++Size  64: 32,64   BAD  (FFFFFF)
++Size  65: 33,65   BAD  (FFFFFF)
++Size  66: 33,66   BAD  (FFFFFF)
++Size  67: 34,67   BAD  (FFFFFF)
++Size  68: 34,68   BAD  (FFFFFF)
++Size  69: 35,69   BAD  (FFFFFF)
++Size  70: 35,70   BAD  (FFFFFF)
++Size  71: 36,71   BAD  (FFFFFF)
++Size  72: 36,72   BAD  (FFFFFF)
++Size  73: 37,73   BAD  (FFFFFF)
++Size  74: 37,74   BAD  (FFFFFF)
++Size  75: 38,75   BAD  (FFFFFF)
++Size  76: 38,76   BAD  (FFFFFF)
++Size  77: 39,77   BAD  (FFFFFF)
++Size  78: 39,78   BAD  (FFFFFF)
++Size  79: 40,79   BAD  (FFFFFF)
++Size  80: 40,80   BAD  (FFFFFF)
++Size  81: 41,81   BAD  (FFFFFF)
++Size  82: 41,82   BAD  (FFFFFF)
++Size  83: 42,83   BAD  (FFFFFF)
++Size  84: 42,84   BAD  (FFFFFF)
++Size  85: 43,85   BAD  (FFFFFF)
++Size  86: 43,86   BAD  (FFFFFF)
++Size  87: 44,87   BAD  (FFFFFF)
++Size  88: 44,88   BAD  (FFFFFF)
++Size  89: 45,89   BAD  (FFFFFF)
++Size  90: 45,90   BAD  (FFFFFF)
++Size  91: 46,91   BAD  (FFFFFF)
++Size  92: 46,92   BAD  (FFFFFF)
++Size  93: 47,93   BAD  (FFFFFF)
++Size  94: 47,94   BAD  (FFFFFF)
++Size  95: 48,95   BAD  (FFFFFF)
++Size  96: 48,97   BAD  (FFFFFF)
++Size  97: 49,97   BAD  (FFFFFF)
++Size  98: 49,98   BAD  (FFFFFF)
++Size  99: 50,99   BAD  (FFFFFF)
++Size 100: 50,100  BAD  (FFFFFF)
++
++Windows 10 14342 New Console
++----------------------------
++
++Size   1: 1,1     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     OK   (HHHFFF)
++Size   4: 2,4     OK   (HHHFFF)
++Size   5: 3,5     OK   (HHHFFF)
++Size   6: 3,6     OK   (HHHFFF)
++Size   7: 4,7     OK   (HHHFFF)
++Size   8: 4,8     OK   (HHHFFF)
++Size   9: 5,9     OK   (HHHFFF)
++Size  10: 5,10    OK   (HHHFFF)
++Size  11: 6,11    OK   (HHHFFF)
++Size  12: 6,12    OK   (HHHFFF)
++Size  13: 7,13    OK   (HHHFFF)
++Size  14: 7,14    OK   (HHHFFF)
++Size  15: 8,15    OK   (HHHFFF)
++Size  16: 8,16    OK   (HHHFFF)
++Size  17: 9,17    OK   (HHHFFF)
++Size  18: 9,18    OK   (HHHFFF)
++Size  19: 10,19   OK   (HHHFFF)
++Size  20: 10,20   OK   (HHHFFF)
++Size  21: 11,21   OK   (HHHFFF)
++Size  22: 11,22   OK   (HHHFFF)
++Size  23: 12,23   OK   (HHHFFF)
++Size  24: 12,24   OK   (HHHFFF)
++Size  25: 13,25   OK   (HHHFFF)
++Size  26: 13,26   OK   (HHHFFF)
++Size  27: 14,27   OK   (HHHFFF)
++Size  28: 14,28   OK   (HHHFFF)
++Size  29: 15,29   OK   (HHHFFF)
++Size  30: 15,30   OK   (HHHFFF)
++Size  31: 16,31   OK   (HHHFFF)
++Size  32: 16,32   OK   (HHHFFF)
++Size  33: 17,33   OK   (HHHFFF)
++Size  34: 17,34   OK   (HHHFFF)
++Size  35: 18,35   OK   (HHHFFF)
++Size  36: 18,36   OK   (HHHFFF)
++Size  37: 19,37   OK   (HHHFFF)
++Size  38: 19,38   OK   (HHHFFF)
++Size  39: 20,39   OK   (HHHFFF)
++Size  40: 20,40   OK   (HHHFFF)
++Size  41: 21,41   OK   (HHHFFF)
++Size  42: 21,42   OK   (HHHFFF)
++Size  43: 22,43   OK   (HHHFFF)
++Size  44: 22,44   OK   (HHHFFF)
++Size  45: 23,45   OK   (HHHFFF)
++Size  46: 23,46   OK   (HHHFFF)
++Size  47: 24,47   OK   (HHHFFF)
++Size  48: 24,48   OK   (HHHFFF)
++Size  49: 25,49   OK   (HHHFFF)
++Size  50: 25,50   OK   (HHHFFF)
++Size  51: 26,51   OK   (HHHFFF)
++Size  52: 26,52   OK   (HHHFFF)
++Size  53: 27,53   OK   (HHHFFF)
++Size  54: 27,54   OK   (HHHFFF)
++Size  55: 28,55   OK   (HHHFFF)
++Size  56: 28,56   OK   (HHHFFF)
++Size  57: 29,57   OK   (HHHFFF)
++Size  58: 29,58   OK   (HHHFFF)
++Size  59: 30,59   OK   (HHHFFF)
++Size  60: 30,60   OK   (HHHFFF)
++Size  61: 31,61   OK   (HHHFFF)
++Size  62: 31,62   OK   (HHHFFF)
++Size  63: 32,63   OK   (HHHFFF)
++Size  64: 32,64   OK   (HHHFFF)
++Size  65: 33,65   OK   (HHHFFF)
++Size  66: 33,66   OK   (HHHFFF)
++Size  67: 34,67   OK   (HHHFFF)
++Size  68: 34,68   OK   (HHHFFF)
++Size  69: 35,69   OK   (HHHFFF)
++Size  70: 35,70   OK   (HHHFFF)
++Size  71: 36,71   OK   (HHHFFF)
++Size  72: 36,72   OK   (HHHFFF)
++Size  73: 37,73   OK   (HHHFFF)
++Size  74: 37,74   OK   (HHHFFF)
++Size  75: 38,75   OK   (HHHFFF)
++Size  76: 38,76   OK   (HHHFFF)
++Size  77: 39,77   OK   (HHHFFF)
++Size  78: 39,78   OK   (HHHFFF)
++Size  79: 40,79   OK   (HHHFFF)
++Size  80: 40,80   OK   (HHHFFF)
++Size  81: 41,81   OK   (HHHFFF)
++Size  82: 41,82   OK   (HHHFFF)
++Size  83: 42,83   OK   (HHHFFF)
++Size  84: 42,84   OK   (HHHFFF)
++Size  85: 43,85   OK   (HHHFFF)
++Size  86: 43,86   OK   (HHHFFF)
++Size  87: 44,87   OK   (HHHFFF)
++Size  88: 44,88   OK   (HHHFFF)
++Size  89: 45,89   OK   (HHHFFF)
++Size  90: 45,90   OK   (HHHFFF)
++Size  91: 46,91   OK   (HHHFFF)
++Size  92: 46,92   OK   (HHHFFF)
++Size  93: 47,93   OK   (HHHFFF)
++Size  94: 47,94   OK   (HHHFFF)
++Size  95: 48,95   OK   (HHHFFF)
++Size  96: 48,96   OK   (HHHFFF)
++Size  97: 49,97   OK   (HHHFFF)
++Size  98: 49,98   OK   (HHHFFF)
++Size  99: 50,99   OK   (HHHFFF)
++Size 100: 50,100  OK   (HHHFFF)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..43210dac51832b374aa7463814d832e4a5f79016
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,630 @@@
++==========================================================
++Code Page 936, Chinese Simplified (China/PRC), SimSun font
++==========================================================
++
++Options: -face-simsun -family 0x36
++Chars: A2 A3 2014 3044 30FC 4000
++
++Vista
++-----
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (HHHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (HHHFHH)
++Size   8: 4,9     GOOD (HHFFFF)
++Size   9: 5,10    BAD  (HHHFHH)
++Size  10: 5,11    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (HHHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,15    BAD  (HHHFHH)
++Size  14: 7,16    GOOD (HHFFFF)
++Size  15: 8,17    BAD  (HHHFHH)
++Size  16: 8,18    GOOD (HHFFFF)
++Size  17: 9,19    BAD  (HHHFHH)
++Size  18: 9,21    GOOD (HHFFFF)
++Size  19: 10,22   BAD  (HHHFHH)
++Size  20: 10,23   GOOD (HHFFFF)
++Size  21: 11,24   BAD  (HHHFHH)
++Size  22: 11,25   GOOD (HHFFFF)
++Size  23: 12,26   BAD  (HHHFHH)
++Size  24: 12,27   GOOD (HHFFFF)
++Size  25: 13,29   BAD  (HHHFHH)
++Size  26: 13,30   GOOD (HHFFFF)
++Size  27: 14,31   BAD  (HHHFHH)
++Size  28: 14,32   GOOD (HHFFFF)
++Size  29: 15,33   BAD  (HHHFHH)
++Size  30: 15,34   GOOD (HHFFFF)
++Size  31: 16,35   BAD  (HHHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,38   BAD  (HHHFHH)
++Size  34: 17,39   GOOD (HHFFFF)
++Size  35: 18,40   BAD  (HHHFHH)
++Size  36: 18,41   GOOD (HHFFFF)
++Size  37: 19,42   BAD  (HHHFHH)
++Size  38: 19,43   GOOD (HHFFFF)
++Size  39: 20,44   BAD  (HHHFHH)
++Size  40: 20,46   GOOD (HHFFFF)
++Size  41: 21,47   BAD  (HHHFHH)
++Size  42: 21,48   GOOD (HHFFFF)
++Size  43: 22,49   BAD  (HHHFHH)
++Size  44: 22,50   GOOD (HHFFFF)
++Size  45: 23,51   BAD  (HHHFHH)
++Size  46: 23,52   GOOD (HHFFFF)
++Size  47: 24,54   BAD  (HHHFHH)
++Size  48: 24,55   GOOD (HHFFFF)
++Size  49: 25,56   BAD  (HHHFHH)
++Size  50: 25,57   GOOD (HHFFFF)
++Size  51: 26,58   BAD  (HHHFHH)
++Size  52: 26,59   GOOD (HHFFFF)
++Size  53: 27,60   BAD  (HHHFHH)
++Size  54: 27,62   GOOD (HHFFFF)
++Size  55: 28,63   BAD  (HHHFHH)
++Size  56: 28,64   GOOD (HHFFFF)
++Size  57: 29,65   BAD  (HHHFHH)
++Size  58: 29,66   GOOD (HHFFFF)
++Size  59: 30,67   BAD  (HHHFHH)
++Size  60: 30,68   GOOD (HHFFFF)
++Size  61: 31,70   BAD  (HHHFHH)
++Size  62: 31,71   GOOD (HHFFFF)
++Size  63: 32,72   BAD  (HHHFHH)
++Size  64: 32,73   GOOD (HHFFFF)
++Size  65: 33,74   GOOD (HHFFFF)
++Size  66: 33,75   GOOD (HHFFFF)
++Size  67: 34,76   GOOD (HHFFFF)
++Size  68: 34,78   GOOD (HHFFFF)
++Size  69: 35,79   GOOD (HHFFFF)
++Size  70: 35,80   GOOD (HHFFFF)
++Size  71: 36,81   GOOD (HHFFFF)
++Size  72: 36,82   GOOD (HHFFFF)
++Size  73: 37,83   GOOD (HHFFFF)
++Size  74: 37,84   GOOD (HHFFFF)
++Size  75: 38,86   GOOD (HHFFFF)
++Size  76: 38,87   GOOD (HHFFFF)
++Size  77: 39,88   GOOD (HHFFFF)
++Size  78: 39,89   GOOD (HHFFFF)
++Size  79: 40,90   GOOD (HHFFFF)
++Size  80: 40,91   GOOD (HHFFFF)
++Size  81: 41,92   GOOD (HHFFFF)
++Size  82: 41,94   GOOD (HHFFFF)
++Size  83: 42,95   GOOD (HHFFFF)
++Size  84: 42,96   GOOD (HHFFFF)
++Size  85: 43,97   GOOD (HHFFFF)
++Size  86: 43,98   GOOD (HHFFFF)
++Size  87: 44,99   GOOD (HHFFFF)
++Size  88: 44,100  GOOD (HHFFFF)
++Size  89: 45,102  GOOD (HHFFFF)
++Size  90: 45,103  GOOD (HHFFFF)
++Size  91: 46,104  GOOD (HHFFFF)
++Size  92: 46,105  GOOD (HHFFFF)
++Size  93: 47,106  GOOD (HHFFFF)
++Size  94: 47,107  GOOD (HHFFFF)
++Size  95: 48,108  GOOD (HHFFFF)
++Size  96: 48,111  GOOD (HHFFFF)
++Size  97: 49,111  GOOD (HHFFFF)
++Size  98: 49,112  GOOD (HHFFFF)
++Size  99: 50,113  GOOD (HHFFFF)
++Size 100: 50,114  GOOD (HHFFFF)
++
++Windows 7
++---------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,9     GOOD (HHFFFF)
++Size   9: 5,10    BAD  (FFHFHH)
++Size  10: 5,11    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,15    BAD  (FFHFHH)
++Size  14: 7,16    GOOD (HHFFFF)
++Size  15: 8,17    BAD  (FFHFHH)
++Size  16: 8,18    GOOD (HHFFFF)
++Size  17: 9,19    BAD  (FFHFHH)
++Size  18: 9,21    GOOD (HHFFFF)
++Size  19: 10,22   BAD  (FFHFHH)
++Size  20: 10,23   GOOD (HHFFFF)
++Size  21: 11,24   BAD  (FFHFHH)
++Size  22: 11,25   GOOD (HHFFFF)
++Size  23: 12,26   BAD  (FFHFHH)
++Size  24: 12,27   GOOD (HHFFFF)
++Size  25: 13,29   BAD  (FFHFHH)
++Size  26: 13,30   GOOD (HHFFFF)
++Size  27: 14,31   BAD  (FFHFHH)
++Size  28: 14,32   GOOD (HHFFFF)
++Size  29: 15,33   BAD  (FFHFHH)
++Size  30: 15,34   GOOD (HHFFFF)
++Size  31: 16,35   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,38   BAD  (FFHFHH)
++Size  34: 17,39   GOOD (HHFFFF)
++Size  35: 18,40   BAD  (FFHFHH)
++Size  36: 18,41   GOOD (HHFFFF)
++Size  37: 19,42   BAD  (FFHFHH)
++Size  38: 19,43   GOOD (HHFFFF)
++Size  39: 20,44   BAD  (FFHFHH)
++Size  40: 20,46   GOOD (HHFFFF)
++Size  41: 21,47   BAD  (FFHFHH)
++Size  42: 21,48   GOOD (HHFFFF)
++Size  43: 22,49   BAD  (FFHFHH)
++Size  44: 22,50   GOOD (HHFFFF)
++Size  45: 23,51   BAD  (FFHFHH)
++Size  46: 23,52   GOOD (HHFFFF)
++Size  47: 24,54   BAD  (FFHFHH)
++Size  48: 24,55   GOOD (HHFFFF)
++Size  49: 25,56   BAD  (FFHFHH)
++Size  50: 25,57   GOOD (HHFFFF)
++Size  51: 26,58   BAD  (FFHFHH)
++Size  52: 26,59   GOOD (HHFFFF)
++Size  53: 27,60   BAD  (FFHFHH)
++Size  54: 27,62   GOOD (HHFFFF)
++Size  55: 28,63   BAD  (FFHFHH)
++Size  56: 28,64   GOOD (HHFFFF)
++Size  57: 29,65   BAD  (FFHFHH)
++Size  58: 29,66   GOOD (HHFFFF)
++Size  59: 30,67   BAD  (FFHFHH)
++Size  60: 30,68   GOOD (HHFFFF)
++Size  61: 31,70   BAD  (FFHFHH)
++Size  62: 31,71   GOOD (HHFFFF)
++Size  63: 32,72   BAD  (FFHFHH)
++Size  64: 32,73   GOOD (HHFFFF)
++Size  65: 33,74   GOOD (HHFFFF)
++Size  66: 33,75   GOOD (HHFFFF)
++Size  67: 34,76   GOOD (HHFFFF)
++Size  68: 34,78   GOOD (HHFFFF)
++Size  69: 35,79   GOOD (HHFFFF)
++Size  70: 35,80   GOOD (HHFFFF)
++Size  71: 36,81   GOOD (HHFFFF)
++Size  72: 36,82   GOOD (HHFFFF)
++Size  73: 37,83   GOOD (HHFFFF)
++Size  74: 37,84   GOOD (HHFFFF)
++Size  75: 38,86   GOOD (HHFFFF)
++Size  76: 38,87   GOOD (HHFFFF)
++Size  77: 39,88   GOOD (HHFFFF)
++Size  78: 39,89   GOOD (HHFFFF)
++Size  79: 40,90   GOOD (HHFFFF)
++Size  80: 40,91   GOOD (HHFFFF)
++Size  81: 41,92   GOOD (HHFFFF)
++Size  82: 41,94   GOOD (HHFFFF)
++Size  83: 42,95   GOOD (HHFFFF)
++Size  84: 42,96   GOOD (HHFFFF)
++Size  85: 43,97   GOOD (HHFFFF)
++Size  86: 43,98   GOOD (HHFFFF)
++Size  87: 44,99   GOOD (HHFFFF)
++Size  88: 44,100  GOOD (HHFFFF)
++Size  89: 45,102  GOOD (HHFFFF)
++Size  90: 45,103  GOOD (HHFFFF)
++Size  91: 46,104  GOOD (HHFFFF)
++Size  92: 46,105  GOOD (HHFFFF)
++Size  93: 47,106  GOOD (HHFFFF)
++Size  94: 47,107  GOOD (HHFFFF)
++Size  95: 48,108  GOOD (HHFFFF)
++Size  96: 48,111  GOOD (HHFFFF)
++Size  97: 49,111  GOOD (HHFFFF)
++Size  98: 49,112  GOOD (HHFFFF)
++Size  99: 50,113  GOOD (HHFFFF)
++Size 100: 50,114  GOOD (HHFFFF)
++
++Windows 8
++---------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,9     GOOD (HHFFFF)
++Size   9: 5,10    BAD  (FFHFHH)
++Size  10: 5,11    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,15    BAD  (FFHFHH)
++Size  14: 7,16    GOOD (HHFFFF)
++Size  15: 8,17    BAD  (FFHFHH)
++Size  16: 8,18    GOOD (HHFFFF)
++Size  17: 9,19    BAD  (FFHFHH)
++Size  18: 9,21    GOOD (HHFFFF)
++Size  19: 10,22   BAD  (FFHFHH)
++Size  20: 10,23   GOOD (HHFFFF)
++Size  21: 11,24   BAD  (FFHFHH)
++Size  22: 11,25   GOOD (HHFFFF)
++Size  23: 12,26   BAD  (FFHFHH)
++Size  24: 12,27   GOOD (HHFFFF)
++Size  25: 13,29   BAD  (FFHFHH)
++Size  26: 13,30   GOOD (HHFFFF)
++Size  27: 14,31   BAD  (FFHFHH)
++Size  28: 14,32   GOOD (HHFFFF)
++Size  29: 15,33   BAD  (FFHFHH)
++Size  30: 15,34   GOOD (HHFFFF)
++Size  31: 16,35   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,38   BAD  (FFHFHH)
++Size  34: 17,39   GOOD (HHFFFF)
++Size  35: 18,40   BAD  (FFHFHH)
++Size  36: 18,41   GOOD (HHFFFF)
++Size  37: 19,42   BAD  (FFHFHH)
++Size  38: 19,43   GOOD (HHFFFF)
++Size  39: 20,44   BAD  (FFHFHH)
++Size  40: 20,46   GOOD (HHFFFF)
++Size  41: 21,47   BAD  (FFHFHH)
++Size  42: 21,48   GOOD (HHFFFF)
++Size  43: 22,49   BAD  (FFHFHH)
++Size  44: 22,50   GOOD (HHFFFF)
++Size  45: 23,51   BAD  (FFHFHH)
++Size  46: 23,52   GOOD (HHFFFF)
++Size  47: 24,54   BAD  (FFHFHH)
++Size  48: 24,55   GOOD (HHFFFF)
++Size  49: 25,56   BAD  (FFHFHH)
++Size  50: 25,57   GOOD (HHFFFF)
++Size  51: 26,58   BAD  (FFHFHH)
++Size  52: 26,59   GOOD (HHFFFF)
++Size  53: 27,60   BAD  (FFHFHH)
++Size  54: 27,62   GOOD (HHFFFF)
++Size  55: 28,63   BAD  (FFHFHH)
++Size  56: 28,64   GOOD (HHFFFF)
++Size  57: 29,65   BAD  (FFHFHH)
++Size  58: 29,66   GOOD (HHFFFF)
++Size  59: 30,67   BAD  (FFHFHH)
++Size  60: 30,68   GOOD (HHFFFF)
++Size  61: 31,70   BAD  (FFHFHH)
++Size  62: 31,71   GOOD (HHFFFF)
++Size  63: 32,72   BAD  (FFHFHH)
++Size  64: 32,73   GOOD (HHFFFF)
++Size  65: 33,74   GOOD (HHFFFF)
++Size  66: 33,75   GOOD (HHFFFF)
++Size  67: 34,76   GOOD (HHFFFF)
++Size  68: 34,78   GOOD (HHFFFF)
++Size  69: 35,79   GOOD (HHFFFF)
++Size  70: 35,80   GOOD (HHFFFF)
++Size  71: 36,81   GOOD (HHFFFF)
++Size  72: 36,82   GOOD (HHFFFF)
++Size  73: 37,83   GOOD (HHFFFF)
++Size  74: 37,84   GOOD (HHFFFF)
++Size  75: 38,86   GOOD (HHFFFF)
++Size  76: 38,87   GOOD (HHFFFF)
++Size  77: 39,88   GOOD (HHFFFF)
++Size  78: 39,89   GOOD (HHFFFF)
++Size  79: 40,90   GOOD (HHFFFF)
++Size  80: 40,91   GOOD (HHFFFF)
++Size  81: 41,92   GOOD (HHFFFF)
++Size  82: 41,94   GOOD (HHFFFF)
++Size  83: 42,95   GOOD (HHFFFF)
++Size  84: 42,96   GOOD (HHFFFF)
++Size  85: 43,97   GOOD (HHFFFF)
++Size  86: 43,98   GOOD (HHFFFF)
++Size  87: 44,99   GOOD (HHFFFF)
++Size  88: 44,100  GOOD (HHFFFF)
++Size  89: 45,102  GOOD (HHFFFF)
++Size  90: 45,103  GOOD (HHFFFF)
++Size  91: 46,104  GOOD (HHFFFF)
++Size  92: 46,105  GOOD (HHFFFF)
++Size  93: 47,106  GOOD (HHFFFF)
++Size  94: 47,107  GOOD (HHFFFF)
++Size  95: 48,108  GOOD (HHFFFF)
++Size  96: 48,111  GOOD (HHFFFF)
++Size  97: 49,111  GOOD (HHFFFF)
++Size  98: 49,112  GOOD (HHFFFF)
++Size  99: 50,113  GOOD (HHFFFF)
++Size 100: 50,114  GOOD (HHFFFF)
++
++Windows 8.1
++-----------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,9     GOOD (HHFFFF)
++Size   9: 5,10    BAD  (FFHFHH)
++Size  10: 5,11    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,15    BAD  (FFHFHH)
++Size  14: 7,16    GOOD (HHFFFF)
++Size  15: 8,17    BAD  (FFHFHH)
++Size  16: 8,18    GOOD (HHFFFF)
++Size  17: 9,19    BAD  (FFHFHH)
++Size  18: 9,21    GOOD (HHFFFF)
++Size  19: 10,22   BAD  (FFHFHH)
++Size  20: 10,23   GOOD (HHFFFF)
++Size  21: 11,24   BAD  (FFHFHH)
++Size  22: 11,25   GOOD (HHFFFF)
++Size  23: 12,26   BAD  (FFHFHH)
++Size  24: 12,27   GOOD (HHFFFF)
++Size  25: 13,29   BAD  (FFHFHH)
++Size  26: 13,30   GOOD (HHFFFF)
++Size  27: 14,31   BAD  (FFHFHH)
++Size  28: 14,32   GOOD (HHFFFF)
++Size  29: 15,33   BAD  (FFHFHH)
++Size  30: 15,34   GOOD (HHFFFF)
++Size  31: 16,35   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,38   BAD  (FFHFHH)
++Size  34: 17,39   GOOD (HHFFFF)
++Size  35: 18,40   BAD  (FFHFHH)
++Size  36: 18,41   GOOD (HHFFFF)
++Size  37: 19,42   BAD  (FFHFHH)
++Size  38: 19,43   GOOD (HHFFFF)
++Size  39: 20,44   BAD  (FFHFHH)
++Size  40: 20,46   GOOD (HHFFFF)
++Size  41: 21,47   BAD  (FFHFHH)
++Size  42: 21,48   GOOD (HHFFFF)
++Size  43: 22,49   BAD  (FFHFHH)
++Size  44: 22,50   GOOD (HHFFFF)
++Size  45: 23,51   BAD  (FFHFHH)
++Size  46: 23,52   GOOD (HHFFFF)
++Size  47: 24,54   BAD  (FFHFHH)
++Size  48: 24,55   GOOD (HHFFFF)
++Size  49: 25,56   BAD  (FFHFHH)
++Size  50: 25,57   GOOD (HHFFFF)
++Size  51: 26,58   BAD  (FFHFHH)
++Size  52: 26,59   GOOD (HHFFFF)
++Size  53: 27,60   BAD  (FFHFHH)
++Size  54: 27,62   GOOD (HHFFFF)
++Size  55: 28,63   BAD  (FFHFHH)
++Size  56: 28,64   GOOD (HHFFFF)
++Size  57: 29,65   BAD  (FFHFHH)
++Size  58: 29,66   GOOD (HHFFFF)
++Size  59: 30,67   BAD  (FFHFHH)
++Size  60: 30,68   GOOD (HHFFFF)
++Size  61: 31,70   BAD  (FFHFHH)
++Size  62: 31,71   GOOD (HHFFFF)
++Size  63: 32,72   BAD  (FFHFHH)
++Size  64: 32,73   GOOD (HHFFFF)
++Size  65: 33,74   GOOD (HHFFFF)
++Size  66: 33,75   GOOD (HHFFFF)
++Size  67: 34,76   GOOD (HHFFFF)
++Size  68: 34,78   GOOD (HHFFFF)
++Size  69: 35,79   GOOD (HHFFFF)
++Size  70: 35,80   GOOD (HHFFFF)
++Size  71: 36,81   GOOD (HHFFFF)
++Size  72: 36,82   GOOD (HHFFFF)
++Size  73: 37,83   GOOD (HHFFFF)
++Size  74: 37,84   GOOD (HHFFFF)
++Size  75: 38,86   GOOD (HHFFFF)
++Size  76: 38,87   GOOD (HHFFFF)
++Size  77: 39,88   GOOD (HHFFFF)
++Size  78: 39,89   GOOD (HHFFFF)
++Size  79: 40,90   GOOD (HHFFFF)
++Size  80: 40,91   GOOD (HHFFFF)
++Size  81: 41,92   GOOD (HHFFFF)
++Size  82: 41,94   GOOD (HHFFFF)
++Size  83: 42,95   GOOD (HHFFFF)
++Size  84: 42,96   GOOD (HHFFFF)
++Size  85: 43,97   GOOD (HHFFFF)
++Size  86: 43,98   GOOD (HHFFFF)
++Size  87: 44,99   GOOD (HHFFFF)
++Size  88: 44,100  GOOD (HHFFFF)
++Size  89: 45,102  GOOD (HHFFFF)
++Size  90: 45,103  GOOD (HHFFFF)
++Size  91: 46,104  GOOD (HHFFFF)
++Size  92: 46,105  GOOD (HHFFFF)
++Size  93: 47,106  GOOD (HHFFFF)
++Size  94: 47,107  GOOD (HHFFFF)
++Size  95: 48,108  GOOD (HHFFFF)
++Size  96: 48,111  GOOD (HHFFFF)
++Size  97: 49,111  GOOD (HHFFFF)
++Size  98: 49,112  GOOD (HHFFFF)
++Size  99: 50,113  GOOD (HHFFFF)
++Size 100: 50,114  GOOD (HHFFFF)
++
++Windows 10 14342 Old Console
++----------------------------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,9     GOOD (HHFFFF)
++Size   9: 5,10    BAD  (FFHFHH)
++Size  10: 5,11    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,15    BAD  (FFHFHH)
++Size  14: 7,16    GOOD (HHFFFF)
++Size  15: 8,17    BAD  (FFHFHH)
++Size  16: 8,18    GOOD (HHFFFF)
++Size  17: 9,19    BAD  (FFHFHH)
++Size  18: 9,21    GOOD (HHFFFF)
++Size  19: 10,22   BAD  (FFHFHH)
++Size  20: 10,23   GOOD (HHFFFF)
++Size  21: 11,24   BAD  (FFHFHH)
++Size  22: 11,25   GOOD (HHFFFF)
++Size  23: 12,26   BAD  (FFHFHH)
++Size  24: 12,27   GOOD (HHFFFF)
++Size  25: 13,29   BAD  (FFHFHH)
++Size  26: 13,30   GOOD (HHFFFF)
++Size  27: 14,31   BAD  (FFHFHH)
++Size  28: 14,32   GOOD (HHFFFF)
++Size  29: 15,33   BAD  (FFHFHH)
++Size  30: 15,34   GOOD (HHFFFF)
++Size  31: 16,35   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,38   BAD  (FFHFHH)
++Size  34: 17,39   GOOD (HHFFFF)
++Size  35: 18,40   BAD  (FFHFHH)
++Size  36: 18,41   GOOD (HHFFFF)
++Size  37: 19,42   BAD  (FFHFHH)
++Size  38: 19,43   GOOD (HHFFFF)
++Size  39: 20,44   BAD  (FFHFHH)
++Size  40: 20,46   GOOD (HHFFFF)
++Size  41: 21,47   BAD  (FFHFHH)
++Size  42: 21,48   GOOD (HHFFFF)
++Size  43: 22,49   BAD  (FFHFHH)
++Size  44: 22,50   GOOD (HHFFFF)
++Size  45: 23,51   BAD  (FFHFHH)
++Size  46: 23,52   GOOD (HHFFFF)
++Size  47: 24,54   BAD  (FFHFHH)
++Size  48: 24,55   GOOD (HHFFFF)
++Size  49: 25,56   BAD  (FFHFHH)
++Size  50: 25,57   GOOD (HHFFFF)
++Size  51: 26,58   BAD  (FFHFHH)
++Size  52: 26,59   GOOD (HHFFFF)
++Size  53: 27,60   BAD  (FFHFHH)
++Size  54: 27,62   GOOD (HHFFFF)
++Size  55: 28,63   BAD  (FFHFHH)
++Size  56: 28,64   GOOD (HHFFFF)
++Size  57: 29,65   BAD  (FFHFHH)
++Size  58: 29,66   GOOD (HHFFFF)
++Size  59: 30,67   BAD  (FFHFHH)
++Size  60: 30,68   GOOD (HHFFFF)
++Size  61: 31,70   BAD  (FFHFHH)
++Size  62: 31,71   GOOD (HHFFFF)
++Size  63: 32,72   BAD  (FFHFHH)
++Size  64: 32,73   GOOD (HHFFFF)
++Size  65: 33,74   GOOD (HHFFFF)
++Size  66: 33,75   GOOD (HHFFFF)
++Size  67: 34,76   GOOD (HHFFFF)
++Size  68: 34,78   GOOD (HHFFFF)
++Size  69: 35,79   GOOD (HHFFFF)
++Size  70: 35,80   GOOD (HHFFFF)
++Size  71: 36,81   GOOD (HHFFFF)
++Size  72: 36,82   GOOD (HHFFFF)
++Size  73: 37,83   GOOD (HHFFFF)
++Size  74: 37,84   GOOD (HHFFFF)
++Size  75: 38,86   GOOD (HHFFFF)
++Size  76: 38,87   GOOD (HHFFFF)
++Size  77: 39,88   GOOD (HHFFFF)
++Size  78: 39,89   GOOD (HHFFFF)
++Size  79: 40,90   GOOD (HHFFFF)
++Size  80: 40,91   GOOD (HHFFFF)
++Size  81: 41,92   GOOD (HHFFFF)
++Size  82: 41,94   GOOD (HHFFFF)
++Size  83: 42,95   GOOD (HHFFFF)
++Size  84: 42,96   GOOD (HHFFFF)
++Size  85: 43,97   GOOD (HHFFFF)
++Size  86: 43,98   GOOD (HHFFFF)
++Size  87: 44,99   GOOD (HHFFFF)
++Size  88: 44,100  GOOD (HHFFFF)
++Size  89: 45,102  GOOD (HHFFFF)
++Size  90: 45,103  GOOD (HHFFFF)
++Size  91: 46,104  GOOD (HHFFFF)
++Size  92: 46,105  GOOD (HHFFFF)
++Size  93: 47,106  GOOD (HHFFFF)
++Size  94: 47,107  GOOD (HHFFFF)
++Size  95: 48,108  GOOD (HHFFFF)
++Size  96: 48,111  GOOD (HHFFFF)
++Size  97: 49,111  GOOD (HHFFFF)
++Size  98: 49,112  GOOD (HHFFFF)
++Size  99: 50,113  GOOD (HHFFFF)
++Size 100: 50,114  GOOD (HHFFFF)
++
++Windows 10 14342 New Console
++----------------------------
++
++Size   1: 1,1     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     GOOD (HHFFFF)
++Size   4: 2,4     GOOD (HHFFFF)
++Size   5: 3,5     GOOD (HHFFFF)
++Size   6: 3,6     GOOD (HHFFFF)
++Size   7: 4,7     GOOD (HHFFFF)
++Size   8: 4,8     GOOD (HHFFFF)
++Size   9: 5,9     GOOD (HHFFFF)
++Size  10: 5,10    GOOD (HHFFFF)
++Size  11: 6,11    GOOD (HHFFFF)
++Size  12: 6,12    GOOD (HHFFFF)
++Size  13: 7,13    GOOD (HHFFFF)
++Size  14: 7,14    GOOD (HHFFFF)
++Size  15: 8,15    GOOD (HHFFFF)
++Size  16: 8,16    GOOD (HHFFFF)
++Size  17: 9,17    GOOD (HHFFFF)
++Size  18: 9,18    GOOD (HHFFFF)
++Size  19: 10,19   GOOD (HHFFFF)
++Size  20: 10,20   GOOD (HHFFFF)
++Size  21: 11,21   GOOD (HHFFFF)
++Size  22: 11,22   GOOD (HHFFFF)
++Size  23: 12,23   GOOD (HHFFFF)
++Size  24: 12,24   GOOD (HHFFFF)
++Size  25: 13,25   GOOD (HHFFFF)
++Size  26: 13,26   GOOD (HHFFFF)
++Size  27: 14,27   GOOD (HHFFFF)
++Size  28: 14,28   GOOD (HHFFFF)
++Size  29: 15,29   GOOD (HHFFFF)
++Size  30: 15,30   GOOD (HHFFFF)
++Size  31: 16,31   GOOD (HHFFFF)
++Size  32: 16,32   GOOD (HHFFFF)
++Size  33: 17,33   GOOD (HHFFFF)
++Size  34: 17,34   GOOD (HHFFFF)
++Size  35: 18,35   GOOD (HHFFFF)
++Size  36: 18,36   GOOD (HHFFFF)
++Size  37: 19,37   GOOD (HHFFFF)
++Size  38: 19,38   GOOD (HHFFFF)
++Size  39: 20,39   GOOD (HHFFFF)
++Size  40: 20,40   GOOD (HHFFFF)
++Size  41: 21,41   GOOD (HHFFFF)
++Size  42: 21,42   GOOD (HHFFFF)
++Size  43: 22,43   GOOD (HHFFFF)
++Size  44: 22,44   GOOD (HHFFFF)
++Size  45: 23,45   GOOD (HHFFFF)
++Size  46: 23,46   GOOD (HHFFFF)
++Size  47: 24,47   GOOD (HHFFFF)
++Size  48: 24,48   GOOD (HHFFFF)
++Size  49: 25,49   GOOD (HHFFFF)
++Size  50: 25,50   GOOD (HHFFFF)
++Size  51: 26,51   GOOD (HHFFFF)
++Size  52: 26,52   GOOD (HHFFFF)
++Size  53: 27,53   GOOD (HHFFFF)
++Size  54: 27,54   GOOD (HHFFFF)
++Size  55: 28,55   GOOD (HHFFFF)
++Size  56: 28,56   GOOD (HHFFFF)
++Size  57: 29,57   GOOD (HHFFFF)
++Size  58: 29,58   GOOD (HHFFFF)
++Size  59: 30,59   GOOD (HHFFFF)
++Size  60: 30,60   GOOD (HHFFFF)
++Size  61: 31,61   GOOD (HHFFFF)
++Size  62: 31,62   GOOD (HHFFFF)
++Size  63: 32,63   GOOD (HHFFFF)
++Size  64: 32,64   GOOD (HHFFFF)
++Size  65: 33,65   GOOD (HHFFFF)
++Size  66: 33,66   GOOD (HHFFFF)
++Size  67: 34,67   GOOD (HHFFFF)
++Size  68: 34,68   GOOD (HHFFFF)
++Size  69: 35,69   GOOD (HHFFFF)
++Size  70: 35,70   GOOD (HHFFFF)
++Size  71: 36,71   GOOD (HHFFFF)
++Size  72: 36,72   GOOD (HHFFFF)
++Size  73: 37,73   GOOD (HHFFFF)
++Size  74: 37,74   GOOD (HHFFFF)
++Size  75: 38,75   GOOD (HHFFFF)
++Size  76: 38,76   GOOD (HHFFFF)
++Size  77: 39,77   GOOD (HHFFFF)
++Size  78: 39,78   GOOD (HHFFFF)
++Size  79: 40,79   GOOD (HHFFFF)
++Size  80: 40,80   GOOD (HHFFFF)
++Size  81: 41,81   GOOD (HHFFFF)
++Size  82: 41,82   GOOD (HHFFFF)
++Size  83: 42,83   GOOD (HHFFFF)
++Size  84: 42,84   GOOD (HHFFFF)
++Size  85: 43,85   GOOD (HHFFFF)
++Size  86: 43,86   GOOD (HHFFFF)
++Size  87: 44,87   GOOD (HHFFFF)
++Size  88: 44,88   GOOD (HHFFFF)
++Size  89: 45,89   GOOD (HHFFFF)
++Size  90: 45,90   GOOD (HHFFFF)
++Size  91: 46,91   GOOD (HHFFFF)
++Size  92: 46,92   GOOD (HHFFFF)
++Size  93: 47,93   GOOD (HHFFFF)
++Size  94: 47,94   GOOD (HHFFFF)
++Size  95: 48,95   GOOD (HHFFFF)
++Size  96: 48,96   GOOD (HHFFFF)
++Size  97: 49,97   GOOD (HHFFFF)
++Size  98: 49,98   GOOD (HHFFFF)
++Size  99: 50,99   GOOD (HHFFFF)
++Size 100: 50,100  GOOD (HHFFFF)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2f0ea1e7c2e301b8ef30be202405b56ceb47f651
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,630 @@@
++=====================================
++Code Page 949, Korean, GulimChe font
++=====================================
++
++Options: -face-gulimche -family 0x36
++Chars: A2 A3 2014 3044 30FC 4000
++
++Vista
++-----
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,5     OK   (HHHFFF)
++Size   5: 3,6     BAD  (HHHFHH)
++Size   6: 3,7     OK   (HHHFFF)
++Size   7: 4,8     BAD  (HHHFHH)
++Size   8: 4,9     OK   (HHHFFF)
++Size   9: 5,10    BAD  (HHHFHH)
++Size  10: 5,11    OK   (HHHFFF)
++Size  11: 6,13    BAD  (HHHFHH)
++Size  12: 6,14    OK   (HHHFFF)
++Size  13: 7,15    BAD  (HHHFHH)
++Size  14: 7,16    OK   (HHHFFF)
++Size  15: 8,17    BAD  (HHHFHH)
++Size  16: 8,18    OK   (HHHFFF)
++Size  17: 9,20    BAD  (HHHFHH)
++Size  18: 9,21    OK   (HHHFFF)
++Size  19: 10,22   BAD  (HHHFHH)
++Size  20: 10,23   OK   (HHHFFF)
++Size  21: 11,24   BAD  (HHHFHH)
++Size  22: 11,25   OK   (HHHFFF)
++Size  23: 12,26   BAD  (HHHFHH)
++Size  24: 12,28   OK   (HHHFFF)
++Size  25: 13,29   BAD  (HHHFHH)
++Size  26: 13,30   OK   (HHHFFF)
++Size  27: 14,31   BAD  (HHHFHH)
++Size  28: 14,32   OK   (HHHFFF)
++Size  29: 15,33   BAD  (HHHFHH)
++Size  30: 15,34   OK   (HHHFFF)
++Size  31: 16,36   BAD  (HHHFHH)
++Size  32: 16,37   OK   (HHHFFF)
++Size  33: 17,38   BAD  (HHHFHH)
++Size  34: 17,39   OK   (HHHFFF)
++Size  35: 18,40   BAD  (HHHFHH)
++Size  36: 18,41   OK   (HHHFFF)
++Size  37: 19,42   BAD  (HHHFHH)
++Size  38: 19,44   OK   (HHHFFF)
++Size  39: 20,45   BAD  (HHHFHH)
++Size  40: 20,46   OK   (HHHFFF)
++Size  41: 21,47   BAD  (HHHFHH)
++Size  42: 21,48   OK   (HHHFFF)
++Size  43: 22,49   BAD  (HHHFHH)
++Size  44: 22,51   OK   (HHHFFF)
++Size  45: 23,52   BAD  (HHHFHH)
++Size  46: 23,53   OK   (HHHFFF)
++Size  47: 24,54   BAD  (HHHFHH)
++Size  48: 24,55   OK   (HHHFFF)
++Size  49: 25,56   BAD  (HHHFHH)
++Size  50: 25,57   OK   (HHHFFF)
++Size  51: 26,59   BAD  (HHHFHH)
++Size  52: 26,60   OK   (HHHFFF)
++Size  53: 27,61   BAD  (HHHFHH)
++Size  54: 27,62   OK   (HHHFFF)
++Size  55: 28,63   BAD  (HHHFHH)
++Size  56: 28,64   OK   (HHHFFF)
++Size  57: 29,65   BAD  (HHHFHH)
++Size  58: 29,67   OK   (HHHFFF)
++Size  59: 30,68   BAD  (HHHFHH)
++Size  60: 30,69   OK   (HHHFFF)
++Size  61: 31,70   BAD  (HHHFHH)
++Size  62: 31,71   OK   (HHHFFF)
++Size  63: 32,72   BAD  (HHHFHH)
++Size  64: 32,74   OK   (HHHFFF)
++Size  65: 33,75   BAD  (HHHFHH)
++Size  66: 33,76   OK   (HHHFFF)
++Size  67: 34,77   BAD  (HHHFHH)
++Size  68: 34,78   OK   (HHHFFF)
++Size  69: 35,79   BAD  (HHHFHH)
++Size  70: 35,80   OK   (HHHFFF)
++Size  71: 36,82   BAD  (HHHFHH)
++Size  72: 36,83   OK   (HHHFFF)
++Size  73: 37,84   BAD  (HHHFHH)
++Size  74: 37,85   OK   (HHHFFF)
++Size  75: 38,86   BAD  (HHHFHH)
++Size  76: 38,87   OK   (HHHFFF)
++Size  77: 39,88   BAD  (HHHFHH)
++Size  78: 39,90   OK   (HHHFFF)
++Size  79: 40,91   BAD  (HHHFHH)
++Size  80: 40,92   OK   (HHHFFF)
++Size  81: 41,93   BAD  (HHHFHH)
++Size  82: 41,94   OK   (HHHFFF)
++Size  83: 42,95   BAD  (HHHFHH)
++Size  84: 42,96   OK   (HHHFFF)
++Size  85: 43,98   BAD  (HHHFHH)
++Size  86: 43,99   OK   (HHHFFF)
++Size  87: 44,100  BAD  (HHHFHH)
++Size  88: 44,101  OK   (HHHFFF)
++Size  89: 45,102  BAD  (HHHFHH)
++Size  90: 45,103  OK   (HHHFFF)
++Size  91: 46,105  BAD  (HHHFHH)
++Size  92: 46,106  OK   (HHHFFF)
++Size  93: 47,107  BAD  (HHHFHH)
++Size  94: 47,108  OK   (HHHFFF)
++Size  95: 48,109  BAD  (HHHFHH)
++Size  96: 48,110  OK   (HHHFFF)
++Size  97: 49,111  BAD  (HHHFHH)
++Size  98: 49,113  OK   (HHHFFF)
++Size  99: 50,114  BAD  (HHHFHH)
++Size 100: 50,115  OK   (HHHFFF)
++
++Windows 7
++---------
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,5     OK   (HHHFFF)
++Size   5: 3,6     BAD  (FFFFHH)
++Size   6: 3,7     OK   (HHHFFF)
++Size   7: 4,8     BAD  (FFFFHH)
++Size   8: 4,9     OK   (HHHFFF)
++Size   9: 5,10    BAD  (FFFFHH)
++Size  10: 5,11    OK   (HHHFFF)
++Size  11: 6,13    BAD  (FFFFHH)
++Size  12: 6,14    OK   (HHHFFF)
++Size  13: 7,15    BAD  (FFFFHH)
++Size  14: 7,16    OK   (HHHFFF)
++Size  15: 8,17    BAD  (FFFFHH)
++Size  16: 8,18    OK   (HHHFFF)
++Size  17: 9,20    BAD  (FFFFHH)
++Size  18: 9,21    OK   (HHHFFF)
++Size  19: 10,22   BAD  (FFFFHH)
++Size  20: 10,23   OK   (HHHFFF)
++Size  21: 11,24   BAD  (FFFFHH)
++Size  22: 11,25   OK   (HHHFFF)
++Size  23: 12,26   BAD  (FFFFHH)
++Size  24: 12,28   OK   (HHHFFF)
++Size  25: 13,29   BAD  (FFFFHH)
++Size  26: 13,30   OK   (HHHFFF)
++Size  27: 14,31   BAD  (FFFFHH)
++Size  28: 14,32   OK   (HHHFFF)
++Size  29: 15,33   BAD  (FFFFHH)
++Size  30: 15,34   OK   (HHHFFF)
++Size  31: 16,36   BAD  (FFFFHH)
++Size  32: 16,37   OK   (HHHFFF)
++Size  33: 17,38   BAD  (FFFFHH)
++Size  34: 17,39   OK   (HHHFFF)
++Size  35: 18,40   BAD  (FFFFHH)
++Size  36: 18,41   OK   (HHHFFF)
++Size  37: 19,42   BAD  (FFFFHH)
++Size  38: 19,44   OK   (HHHFFF)
++Size  39: 20,45   BAD  (FFFFHH)
++Size  40: 20,46   OK   (HHHFFF)
++Size  41: 21,47   BAD  (FFFFHH)
++Size  42: 21,48   OK   (HHHFFF)
++Size  43: 22,49   BAD  (FFFFHH)
++Size  44: 22,51   OK   (HHHFFF)
++Size  45: 23,52   BAD  (FFFFHH)
++Size  46: 23,53   OK   (HHHFFF)
++Size  47: 24,54   BAD  (FFFFHH)
++Size  48: 24,55   OK   (HHHFFF)
++Size  49: 25,56   BAD  (FFFFHH)
++Size  50: 25,57   OK   (HHHFFF)
++Size  51: 26,59   BAD  (FFFFHH)
++Size  52: 26,60   OK   (HHHFFF)
++Size  53: 27,61   BAD  (FFFFHH)
++Size  54: 27,62   OK   (HHHFFF)
++Size  55: 28,63   BAD  (FFFFHH)
++Size  56: 28,64   OK   (HHHFFF)
++Size  57: 29,65   BAD  (FFFFHH)
++Size  58: 29,67   OK   (HHHFFF)
++Size  59: 30,68   BAD  (FFFFHH)
++Size  60: 30,69   OK   (HHHFFF)
++Size  61: 31,70   BAD  (FFFFHH)
++Size  62: 31,71   OK   (HHHFFF)
++Size  63: 32,72   BAD  (FFFFHH)
++Size  64: 32,74   OK   (HHHFFF)
++Size  65: 33,75   BAD  (FFFFHH)
++Size  66: 33,76   OK   (HHHFFF)
++Size  67: 34,77   BAD  (FFFFHH)
++Size  68: 34,78   OK   (HHHFFF)
++Size  69: 35,79   BAD  (FFFFHH)
++Size  70: 35,80   OK   (HHHFFF)
++Size  71: 36,82   BAD  (FFFFHH)
++Size  72: 36,83   OK   (HHHFFF)
++Size  73: 37,84   BAD  (FFFFHH)
++Size  74: 37,85   OK   (HHHFFF)
++Size  75: 38,86   BAD  (FFFFHH)
++Size  76: 38,87   OK   (HHHFFF)
++Size  77: 39,88   BAD  (FFFFHH)
++Size  78: 39,90   OK   (HHHFFF)
++Size  79: 40,91   BAD  (FFFFHH)
++Size  80: 40,92   OK   (HHHFFF)
++Size  81: 41,93   BAD  (FFFFHH)
++Size  82: 41,94   OK   (HHHFFF)
++Size  83: 42,95   BAD  (FFFFHH)
++Size  84: 42,96   OK   (HHHFFF)
++Size  85: 43,98   BAD  (FFFFHH)
++Size  86: 43,99   OK   (HHHFFF)
++Size  87: 44,100  BAD  (FFFFHH)
++Size  88: 44,101  OK   (HHHFFF)
++Size  89: 45,102  BAD  (FFFFHH)
++Size  90: 45,103  OK   (HHHFFF)
++Size  91: 46,105  BAD  (FFFFHH)
++Size  92: 46,106  OK   (HHHFFF)
++Size  93: 47,107  BAD  (FFFFHH)
++Size  94: 47,108  OK   (HHHFFF)
++Size  95: 48,109  BAD  (FFFFHH)
++Size  96: 48,110  OK   (HHHFFF)
++Size  97: 49,111  BAD  (FFFFHH)
++Size  98: 49,113  OK   (HHHFFF)
++Size  99: 50,114  BAD  (FFFFHH)
++Size 100: 50,115  OK   (HHHFFF)
++
++Windows 8
++---------
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,5     OK   (HHHFFF)
++Size   5: 3,6     BAD  (FFFFHH)
++Size   6: 3,7     OK   (HHHFFF)
++Size   7: 4,8     BAD  (FFFFHH)
++Size   8: 4,9     OK   (HHHFFF)
++Size   9: 5,10    BAD  (FFFFHH)
++Size  10: 5,11    OK   (HHHFFF)
++Size  11: 6,13    BAD  (FFFFHH)
++Size  12: 6,14    OK   (HHHFFF)
++Size  13: 7,15    BAD  (FFFFHH)
++Size  14: 7,16    OK   (HHHFFF)
++Size  15: 8,17    BAD  (FFFFHH)
++Size  16: 8,18    OK   (HHHFFF)
++Size  17: 9,20    BAD  (FFFFHH)
++Size  18: 9,21    OK   (HHHFFF)
++Size  19: 10,22   BAD  (FFFFHH)
++Size  20: 10,23   OK   (HHHFFF)
++Size  21: 11,24   BAD  (FFFFHH)
++Size  22: 11,25   OK   (HHHFFF)
++Size  23: 12,26   BAD  (FFFFHH)
++Size  24: 12,28   OK   (HHHFFF)
++Size  25: 13,29   BAD  (FFFFHH)
++Size  26: 13,30   OK   (HHHFFF)
++Size  27: 14,31   BAD  (FFFFHH)
++Size  28: 14,32   OK   (HHHFFF)
++Size  29: 15,33   BAD  (FFFFHH)
++Size  30: 15,34   OK   (HHHFFF)
++Size  31: 16,36   BAD  (FFFFHH)
++Size  32: 16,37   OK   (HHHFFF)
++Size  33: 17,38   BAD  (FFFFHH)
++Size  34: 17,39   OK   (HHHFFF)
++Size  35: 18,40   BAD  (FFFFHH)
++Size  36: 18,41   OK   (HHHFFF)
++Size  37: 19,42   BAD  (FFFFHH)
++Size  38: 19,44   OK   (HHHFFF)
++Size  39: 20,45   BAD  (FFFFHH)
++Size  40: 20,46   OK   (HHHFFF)
++Size  41: 21,47   BAD  (FFFFHH)
++Size  42: 21,48   OK   (HHHFFF)
++Size  43: 22,49   BAD  (FFFFHH)
++Size  44: 22,51   OK   (HHHFFF)
++Size  45: 23,52   BAD  (FFFFHH)
++Size  46: 23,53   OK   (HHHFFF)
++Size  47: 24,54   BAD  (FFFFHH)
++Size  48: 24,55   OK   (HHHFFF)
++Size  49: 25,56   BAD  (FFFFHH)
++Size  50: 25,57   OK   (HHHFFF)
++Size  51: 26,59   BAD  (FFFFHH)
++Size  52: 26,60   OK   (HHHFFF)
++Size  53: 27,61   BAD  (FFFFHH)
++Size  54: 27,62   OK   (HHHFFF)
++Size  55: 28,63   BAD  (FFFFHH)
++Size  56: 28,64   OK   (HHHFFF)
++Size  57: 29,65   BAD  (FFFFHH)
++Size  58: 29,67   OK   (HHHFFF)
++Size  59: 30,68   BAD  (FFFFHH)
++Size  60: 30,69   OK   (HHHFFF)
++Size  61: 31,70   BAD  (FFFFHH)
++Size  62: 31,71   OK   (HHHFFF)
++Size  63: 32,72   BAD  (FFFFHH)
++Size  64: 32,74   OK   (HHHFFF)
++Size  65: 33,75   BAD  (FFFFHH)
++Size  66: 33,76   OK   (HHHFFF)
++Size  67: 34,77   BAD  (FFFFHH)
++Size  68: 34,78   OK   (HHHFFF)
++Size  69: 35,79   BAD  (FFFFHH)
++Size  70: 35,80   OK   (HHHFFF)
++Size  71: 36,82   BAD  (FFFFHH)
++Size  72: 36,83   OK   (HHHFFF)
++Size  73: 37,84   BAD  (FFFFHH)
++Size  74: 37,85   OK   (HHHFFF)
++Size  75: 38,86   BAD  (FFFFHH)
++Size  76: 38,87   OK   (HHHFFF)
++Size  77: 39,88   BAD  (FFFFHH)
++Size  78: 39,90   OK   (HHHFFF)
++Size  79: 40,91   BAD  (FFFFHH)
++Size  80: 40,92   OK   (HHHFFF)
++Size  81: 41,93   BAD  (FFFFHH)
++Size  82: 41,94   OK   (HHHFFF)
++Size  83: 42,95   BAD  (FFFFHH)
++Size  84: 42,96   OK   (HHHFFF)
++Size  85: 43,98   BAD  (FFFFHH)
++Size  86: 43,99   OK   (HHHFFF)
++Size  87: 44,100  BAD  (FFFFHH)
++Size  88: 44,101  OK   (HHHFFF)
++Size  89: 45,102  BAD  (FFFFHH)
++Size  90: 45,103  OK   (HHHFFF)
++Size  91: 46,105  BAD  (FFFFHH)
++Size  92: 46,106  OK   (HHHFFF)
++Size  93: 47,107  BAD  (FFFFHH)
++Size  94: 47,108  OK   (HHHFFF)
++Size  95: 48,109  BAD  (FFFFHH)
++Size  96: 48,110  OK   (HHHFFF)
++Size  97: 49,111  BAD  (FFFFHH)
++Size  98: 49,113  OK   (HHHFFF)
++Size  99: 50,114  BAD  (FFFFHH)
++Size 100: 50,115  OK   (HHHFFF)
++
++Windows 8.1
++-----------
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,5     OK   (HHHFFF)
++Size   5: 3,6     BAD  (FFFFHH)
++Size   6: 3,7     OK   (HHHFFF)
++Size   7: 4,8     BAD  (FFFFHH)
++Size   8: 4,9     OK   (HHHFFF)
++Size   9: 5,10    BAD  (FFFFHH)
++Size  10: 5,11    OK   (HHHFFF)
++Size  11: 6,13    BAD  (FFFFHH)
++Size  12: 6,14    OK   (HHHFFF)
++Size  13: 7,15    BAD  (FFFFHH)
++Size  14: 7,16    OK   (HHHFFF)
++Size  15: 8,17    BAD  (FFFFHH)
++Size  16: 8,18    OK   (HHHFFF)
++Size  17: 9,20    BAD  (FFFFHH)
++Size  18: 9,21    OK   (HHHFFF)
++Size  19: 10,22   BAD  (FFFFHH)
++Size  20: 10,23   OK   (HHHFFF)
++Size  21: 11,24   BAD  (FFFFHH)
++Size  22: 11,25   OK   (HHHFFF)
++Size  23: 12,26   BAD  (FFFFHH)
++Size  24: 12,28   OK   (HHHFFF)
++Size  25: 13,29   BAD  (FFFFHH)
++Size  26: 13,30   OK   (HHHFFF)
++Size  27: 14,31   BAD  (FFFFHH)
++Size  28: 14,32   OK   (HHHFFF)
++Size  29: 15,33   BAD  (FFFFHH)
++Size  30: 15,34   OK   (HHHFFF)
++Size  31: 16,36   BAD  (FFFFHH)
++Size  32: 16,37   OK   (HHHFFF)
++Size  33: 17,38   BAD  (FFFFHH)
++Size  34: 17,39   OK   (HHHFFF)
++Size  35: 18,40   BAD  (FFFFHH)
++Size  36: 18,41   OK   (HHHFFF)
++Size  37: 19,42   BAD  (FFFFHH)
++Size  38: 19,44   OK   (HHHFFF)
++Size  39: 20,45   BAD  (FFFFHH)
++Size  40: 20,46   OK   (HHHFFF)
++Size  41: 21,47   BAD  (FFFFHH)
++Size  42: 21,48   OK   (HHHFFF)
++Size  43: 22,49   BAD  (FFFFHH)
++Size  44: 22,51   OK   (HHHFFF)
++Size  45: 23,52   BAD  (FFFFHH)
++Size  46: 23,53   OK   (HHHFFF)
++Size  47: 24,54   BAD  (FFFFHH)
++Size  48: 24,55   OK   (HHHFFF)
++Size  49: 25,56   BAD  (FFFFHH)
++Size  50: 25,57   OK   (HHHFFF)
++Size  51: 26,59   BAD  (FFFFHH)
++Size  52: 26,60   OK   (HHHFFF)
++Size  53: 27,61   BAD  (FFFFHH)
++Size  54: 27,62   OK   (HHHFFF)
++Size  55: 28,63   BAD  (FFFFHH)
++Size  56: 28,64   OK   (HHHFFF)
++Size  57: 29,65   BAD  (FFFFHH)
++Size  58: 29,67   OK   (HHHFFF)
++Size  59: 30,68   BAD  (FFFFHH)
++Size  60: 30,69   OK   (HHHFFF)
++Size  61: 31,70   BAD  (FFFFHH)
++Size  62: 31,71   OK   (HHHFFF)
++Size  63: 32,72   BAD  (FFFFHH)
++Size  64: 32,74   OK   (HHHFFF)
++Size  65: 33,75   BAD  (FFFFHH)
++Size  66: 33,76   OK   (HHHFFF)
++Size  67: 34,77   BAD  (FFFFHH)
++Size  68: 34,78   OK   (HHHFFF)
++Size  69: 35,79   BAD  (FFFFHH)
++Size  70: 35,80   OK   (HHHFFF)
++Size  71: 36,82   BAD  (FFFFHH)
++Size  72: 36,83   OK   (HHHFFF)
++Size  73: 37,84   BAD  (FFFFHH)
++Size  74: 37,85   OK   (HHHFFF)
++Size  75: 38,86   BAD  (FFFFHH)
++Size  76: 38,87   OK   (HHHFFF)
++Size  77: 39,88   BAD  (FFFFHH)
++Size  78: 39,90   OK   (HHHFFF)
++Size  79: 40,91   BAD  (FFFFHH)
++Size  80: 40,92   OK   (HHHFFF)
++Size  81: 41,93   BAD  (FFFFHH)
++Size  82: 41,94   OK   (HHHFFF)
++Size  83: 42,95   BAD  (FFFFHH)
++Size  84: 42,96   OK   (HHHFFF)
++Size  85: 43,98   BAD  (FFFFHH)
++Size  86: 43,99   OK   (HHHFFF)
++Size  87: 44,100  BAD  (FFFFHH)
++Size  88: 44,101  OK   (HHHFFF)
++Size  89: 45,102  BAD  (FFFFHH)
++Size  90: 45,103  OK   (HHHFFF)
++Size  91: 46,105  BAD  (FFFFHH)
++Size  92: 46,106  OK   (HHHFFF)
++Size  93: 47,107  BAD  (FFFFHH)
++Size  94: 47,108  OK   (HHHFFF)
++Size  95: 48,109  BAD  (FFFFHH)
++Size  96: 48,110  OK   (HHHFFF)
++Size  97: 49,111  BAD  (FFFFHH)
++Size  98: 49,113  OK   (HHHFFF)
++Size  99: 50,114  BAD  (FFFFHH)
++Size 100: 50,115  OK   (HHHFFF)
++
++Windows 10 14342 Old Console
++----------------------------
++
++Size   1: 1,2     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     BAD  (FFFFHH)
++Size   4: 2,5     OK   (HHHFFF)
++Size   5: 3,6     BAD  (FFFFHH)
++Size   6: 3,7     OK   (HHHFFF)
++Size   7: 4,8     BAD  (FFFFHH)
++Size   8: 4,9     OK   (HHHFFF)
++Size   9: 5,10    BAD  (FFFFHH)
++Size  10: 5,11    OK   (HHHFFF)
++Size  11: 6,13    BAD  (FFFFHH)
++Size  12: 6,14    OK   (HHHFFF)
++Size  13: 7,15    BAD  (FFFFHH)
++Size  14: 7,16    OK   (HHHFFF)
++Size  15: 8,17    BAD  (FFFFHH)
++Size  16: 8,18    OK   (HHHFFF)
++Size  17: 9,20    BAD  (FFFFHH)
++Size  18: 9,21    OK   (HHHFFF)
++Size  19: 10,22   BAD  (FFFFHH)
++Size  20: 10,23   OK   (HHHFFF)
++Size  21: 11,24   BAD  (FFFFHH)
++Size  22: 11,25   OK   (HHHFFF)
++Size  23: 12,26   BAD  (FFFFHH)
++Size  24: 12,28   OK   (HHHFFF)
++Size  25: 13,29   BAD  (FFFFHH)
++Size  26: 13,30   OK   (HHHFFF)
++Size  27: 14,31   BAD  (FFFFHH)
++Size  28: 14,32   OK   (HHHFFF)
++Size  29: 15,33   BAD  (FFFFHH)
++Size  30: 15,34   OK   (HHHFFF)
++Size  31: 16,36   BAD  (FFFFHH)
++Size  32: 16,37   OK   (HHHFFF)
++Size  33: 17,38   BAD  (FFFFHH)
++Size  34: 17,39   OK   (HHHFFF)
++Size  35: 18,40   BAD  (FFFFHH)
++Size  36: 18,41   OK   (HHHFFF)
++Size  37: 19,42   BAD  (FFFFHH)
++Size  38: 19,44   OK   (HHHFFF)
++Size  39: 20,45   BAD  (FFFFHH)
++Size  40: 20,46   OK   (HHHFFF)
++Size  41: 21,47   BAD  (FFFFHH)
++Size  42: 21,48   OK   (HHHFFF)
++Size  43: 22,49   BAD  (FFFFHH)
++Size  44: 22,51   OK   (HHHFFF)
++Size  45: 23,52   BAD  (FFFFHH)
++Size  46: 23,53   OK   (HHHFFF)
++Size  47: 24,54   BAD  (FFFFHH)
++Size  48: 24,55   OK   (HHHFFF)
++Size  49: 25,56   BAD  (FFFFHH)
++Size  50: 25,57   OK   (HHHFFF)
++Size  51: 26,59   BAD  (FFFFHH)
++Size  52: 26,60   OK   (HHHFFF)
++Size  53: 27,61   BAD  (FFFFHH)
++Size  54: 27,62   OK   (HHHFFF)
++Size  55: 28,63   BAD  (FFFFHH)
++Size  56: 28,64   OK   (HHHFFF)
++Size  57: 29,65   BAD  (FFFFHH)
++Size  58: 29,67   OK   (HHHFFF)
++Size  59: 30,68   BAD  (FFFFHH)
++Size  60: 30,69   OK   (HHHFFF)
++Size  61: 31,70   BAD  (FFFFHH)
++Size  62: 31,71   OK   (HHHFFF)
++Size  63: 32,72   BAD  (FFFFHH)
++Size  64: 32,74   OK   (HHHFFF)
++Size  65: 33,75   BAD  (FFFFHH)
++Size  66: 33,76   OK   (HHHFFF)
++Size  67: 34,77   BAD  (FFFFHH)
++Size  68: 34,78   OK   (HHHFFF)
++Size  69: 35,79   BAD  (FFFFHH)
++Size  70: 35,80   OK   (HHHFFF)
++Size  71: 36,82   BAD  (FFFFHH)
++Size  72: 36,83   OK   (HHHFFF)
++Size  73: 37,84   BAD  (FFFFHH)
++Size  74: 37,85   OK   (HHHFFF)
++Size  75: 38,86   BAD  (FFFFHH)
++Size  76: 38,87   OK   (HHHFFF)
++Size  77: 39,88   BAD  (FFFFHH)
++Size  78: 39,90   OK   (HHHFFF)
++Size  79: 40,91   BAD  (FFFFHH)
++Size  80: 40,92   OK   (HHHFFF)
++Size  81: 41,93   BAD  (FFFFHH)
++Size  82: 41,94   OK   (HHHFFF)
++Size  83: 42,95   BAD  (FFFFHH)
++Size  84: 42,96   OK   (HHHFFF)
++Size  85: 43,98   BAD  (FFFFHH)
++Size  86: 43,99   OK   (HHHFFF)
++Size  87: 44,100  BAD  (FFFFHH)
++Size  88: 44,101  OK   (HHHFFF)
++Size  89: 45,102  BAD  (FFFFHH)
++Size  90: 45,103  OK   (HHHFFF)
++Size  91: 46,105  BAD  (FFFFHH)
++Size  92: 46,106  OK   (HHHFFF)
++Size  93: 47,107  BAD  (FFFFHH)
++Size  94: 47,108  OK   (HHHFFF)
++Size  95: 48,109  BAD  (FFFFHH)
++Size  96: 48,110  OK   (HHHFFF)
++Size  97: 49,111  BAD  (FFFFHH)
++Size  98: 49,113  OK   (HHHFFF)
++Size  99: 50,114  BAD  (FFFFHH)
++Size 100: 50,115  OK   (HHHFFF)
++
++Windows 10 14342 New Console
++----------------------------
++
++Size   1: 1,1     OK   (HHHFFF)
++Size   2: 1,2     OK   (HHHFFF)
++Size   3: 2,3     OK   (HHHFFF)
++Size   4: 2,4     OK   (HHHFFF)
++Size   5: 3,5     OK   (HHHFFF)
++Size   6: 3,6     OK   (HHHFFF)
++Size   7: 4,7     OK   (HHHFFF)
++Size   8: 4,8     OK   (HHHFFF)
++Size   9: 5,9     OK   (HHHFFF)
++Size  10: 5,10    OK   (HHHFFF)
++Size  11: 6,11    OK   (HHHFFF)
++Size  12: 6,12    OK   (HHHFFF)
++Size  13: 7,13    OK   (HHHFFF)
++Size  14: 7,14    OK   (HHHFFF)
++Size  15: 8,15    OK   (HHHFFF)
++Size  16: 8,16    OK   (HHHFFF)
++Size  17: 9,17    OK   (HHHFFF)
++Size  18: 9,18    OK   (HHHFFF)
++Size  19: 10,19   OK   (HHHFFF)
++Size  20: 10,20   OK   (HHHFFF)
++Size  21: 11,21   OK   (HHHFFF)
++Size  22: 11,22   OK   (HHHFFF)
++Size  23: 12,23   OK   (HHHFFF)
++Size  24: 12,24   OK   (HHHFFF)
++Size  25: 13,25   OK   (HHHFFF)
++Size  26: 13,26   OK   (HHHFFF)
++Size  27: 14,27   OK   (HHHFFF)
++Size  28: 14,28   OK   (HHHFFF)
++Size  29: 15,29   OK   (HHHFFF)
++Size  30: 15,30   OK   (HHHFFF)
++Size  31: 16,31   OK   (HHHFFF)
++Size  32: 16,32   OK   (HHHFFF)
++Size  33: 17,33   OK   (HHHFFF)
++Size  34: 17,34   OK   (HHHFFF)
++Size  35: 18,35   OK   (HHHFFF)
++Size  36: 18,36   OK   (HHHFFF)
++Size  37: 19,37   OK   (HHHFFF)
++Size  38: 19,38   OK   (HHHFFF)
++Size  39: 20,39   OK   (HHHFFF)
++Size  40: 20,40   OK   (HHHFFF)
++Size  41: 21,41   OK   (HHHFFF)
++Size  42: 21,42   OK   (HHHFFF)
++Size  43: 22,43   OK   (HHHFFF)
++Size  44: 22,44   OK   (HHHFFF)
++Size  45: 23,45   OK   (HHHFFF)
++Size  46: 23,46   OK   (HHHFFF)
++Size  47: 24,47   OK   (HHHFFF)
++Size  48: 24,48   OK   (HHHFFF)
++Size  49: 25,49   OK   (HHHFFF)
++Size  50: 25,50   OK   (HHHFFF)
++Size  51: 26,51   OK   (HHHFFF)
++Size  52: 26,52   OK   (HHHFFF)
++Size  53: 27,53   OK   (HHHFFF)
++Size  54: 27,54   OK   (HHHFFF)
++Size  55: 28,55   OK   (HHHFFF)
++Size  56: 28,56   OK   (HHHFFF)
++Size  57: 29,57   OK   (HHHFFF)
++Size  58: 29,58   OK   (HHHFFF)
++Size  59: 30,59   OK   (HHHFFF)
++Size  60: 30,60   OK   (HHHFFF)
++Size  61: 31,61   OK   (HHHFFF)
++Size  62: 31,62   OK   (HHHFFF)
++Size  63: 32,63   OK   (HHHFFF)
++Size  64: 32,64   OK   (HHHFFF)
++Size  65: 33,65   OK   (HHHFFF)
++Size  66: 33,66   OK   (HHHFFF)
++Size  67: 34,67   OK   (HHHFFF)
++Size  68: 34,68   OK   (HHHFFF)
++Size  69: 35,69   OK   (HHHFFF)
++Size  70: 35,70   OK   (HHHFFF)
++Size  71: 36,71   OK   (HHHFFF)
++Size  72: 36,72   OK   (HHHFFF)
++Size  73: 37,73   OK   (HHHFFF)
++Size  74: 37,74   OK   (HHHFFF)
++Size  75: 38,75   OK   (HHHFFF)
++Size  76: 38,76   OK   (HHHFFF)
++Size  77: 39,77   OK   (HHHFFF)
++Size  78: 39,78   OK   (HHHFFF)
++Size  79: 40,79   OK   (HHHFFF)
++Size  80: 40,80   OK   (HHHFFF)
++Size  81: 41,81   OK   (HHHFFF)
++Size  82: 41,82   OK   (HHHFFF)
++Size  83: 42,83   OK   (HHHFFF)
++Size  84: 42,84   OK   (HHHFFF)
++Size  85: 43,85   OK   (HHHFFF)
++Size  86: 43,86   OK   (HHHFFF)
++Size  87: 44,87   OK   (HHHFFF)
++Size  88: 44,88   OK   (HHHFFF)
++Size  89: 45,89   OK   (HHHFFF)
++Size  90: 45,90   OK   (HHHFFF)
++Size  91: 46,91   OK   (HHHFFF)
++Size  92: 46,92   OK   (HHHFFF)
++Size  93: 47,93   OK   (HHHFFF)
++Size  94: 47,94   OK   (HHHFFF)
++Size  95: 48,95   OK   (HHHFFF)
++Size  96: 48,96   OK   (HHHFFF)
++Size  97: 49,97   OK   (HHHFFF)
++Size  98: 49,98   OK   (HHHFFF)
++Size  99: 50,99   OK   (HHHFFF)
++Size 100: 50,100  OK   (HHHFFF)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0dbade504dbff1c1943c470f82be67ce936c45da
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,630 @@@
++===========================================================
++Code Page 950, Chinese Traditional (Taiwan), MingLight font
++===========================================================
++
++Options: -face-minglight -family 0x36
++Chars: A2 A3 2014 3044 30FC 4000
++
++Vista
++-----
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,4     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (HHHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (HHHFHH)
++Size   8: 4,10    GOOD (HHFFFF)
++Size   9: 5,11    BAD  (HHHFHH)
++Size  10: 5,12    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (HHHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,16    BAD  (HHHFHH)
++Size  14: 7,17    GOOD (HHFFFF)
++Size  15: 8,18    BAD  (HHHFHH)
++Size  16: 8,19    GOOD (HHFFFF)
++Size  17: 9,20    BAD  (HHHFHH)
++Size  18: 9,22    GOOD (HHFFFF)
++Size  19: 10,23   BAD  (HHHFHH)
++Size  20: 10,24   GOOD (HHFFFF)
++Size  21: 11,25   BAD  (HHHFHH)
++Size  22: 11,26   GOOD (HHFFFF)
++Size  23: 12,28   BAD  (HHHFHH)
++Size  24: 12,29   GOOD (HHFFFF)
++Size  25: 13,30   BAD  (HHHFHH)
++Size  26: 13,31   GOOD (HHFFFF)
++Size  27: 14,32   BAD  (HHHFHH)
++Size  28: 14,34   GOOD (HHFFFF)
++Size  29: 15,35   BAD  (HHHFHH)
++Size  30: 15,36   GOOD (HHFFFF)
++Size  31: 16,37   BAD  (HHHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,40   BAD  (HHHFHH)
++Size  34: 17,41   GOOD (HHFFFF)
++Size  35: 18,42   BAD  (HHHFHH)
++Size  36: 18,43   GOOD (HHFFFF)
++Size  37: 19,44   BAD  (HHHFHH)
++Size  38: 19,46   GOOD (HHFFFF)
++Size  39: 20,47   BAD  (HHHFHH)
++Size  40: 20,48   GOOD (HHFFFF)
++Size  41: 21,49   BAD  (HHHFHH)
++Size  42: 21,50   GOOD (HHFFFF)
++Size  43: 22,52   BAD  (HHHFHH)
++Size  44: 22,53   GOOD (HHFFFF)
++Size  45: 23,54   BAD  (HHHFHH)
++Size  46: 23,55   GOOD (HHFFFF)
++Size  47: 24,56   BAD  (HHHFHH)
++Size  48: 24,58   GOOD (HHFFFF)
++Size  49: 25,59   BAD  (HHHFHH)
++Size  50: 25,60   GOOD (HHFFFF)
++Size  51: 26,61   BAD  (HHHFHH)
++Size  52: 26,62   GOOD (HHFFFF)
++Size  53: 27,64   BAD  (HHHFHH)
++Size  54: 27,65   GOOD (HHFFFF)
++Size  55: 28,66   BAD  (HHHFHH)
++Size  56: 28,67   GOOD (HHFFFF)
++Size  57: 29,68   BAD  (HHHFHH)
++Size  58: 29,70   GOOD (HHFFFF)
++Size  59: 30,71   BAD  (HHHFHH)
++Size  60: 30,72   GOOD (HHFFFF)
++Size  61: 31,73   BAD  (HHHFHH)
++Size  62: 31,74   GOOD (HHFFFF)
++Size  63: 32,76   BAD  (HHHFHH)
++Size  64: 32,77   GOOD (HHFFFF)
++Size  65: 33,78   BAD  (HHHFHH)
++Size  66: 33,79   GOOD (HHFFFF)
++Size  67: 34,80   BAD  (HHHFHH)
++Size  68: 34,82   GOOD (HHFFFF)
++Size  69: 35,83   BAD  (HHHFHH)
++Size  70: 35,84   GOOD (HHFFFF)
++Size  71: 36,85   BAD  (HHHFHH)
++Size  72: 36,86   GOOD (HHFFFF)
++Size  73: 37,88   BAD  (HHHFHH)
++Size  74: 37,89   GOOD (HHFFFF)
++Size  75: 38,90   BAD  (HHHFHH)
++Size  76: 38,91   GOOD (HHFFFF)
++Size  77: 39,92   BAD  (HHHFHH)
++Size  78: 39,94   GOOD (HHFFFF)
++Size  79: 40,95   BAD  (HHHFHH)
++Size  80: 40,96   GOOD (HHFFFF)
++Size  81: 41,97   BAD  (HHHFHH)
++Size  82: 41,98   GOOD (HHFFFF)
++Size  83: 42,100  BAD  (HHHFHH)
++Size  84: 42,101  GOOD (HHFFFF)
++Size  85: 43,102  BAD  (HHHFHH)
++Size  86: 43,103  GOOD (HHFFFF)
++Size  87: 44,104  BAD  (HHHFHH)
++Size  88: 44,106  GOOD (HHFFFF)
++Size  89: 45,107  BAD  (HHHFHH)
++Size  90: 45,108  GOOD (HHFFFF)
++Size  91: 46,109  BAD  (HHHFHH)
++Size  92: 46,110  GOOD (HHFFFF)
++Size  93: 47,112  BAD  (HHHFHH)
++Size  94: 47,113  GOOD (HHFFFF)
++Size  95: 48,114  BAD  (HHHFHH)
++Size  96: 48,115  GOOD (HHFFFF)
++Size  97: 49,116  BAD  (HHHFHH)
++Size  98: 49,118  GOOD (HHFFFF)
++Size  99: 50,119  BAD  (HHHFHH)
++Size 100: 50,120  GOOD (HHFFFF)
++
++Windows 7
++---------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,4     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,10    GOOD (HHFFFF)
++Size   9: 5,11    BAD  (FFHFHH)
++Size  10: 5,12    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,16    BAD  (FFHFHH)
++Size  14: 7,17    GOOD (HHFFFF)
++Size  15: 8,18    BAD  (FFHFHH)
++Size  16: 8,19    GOOD (HHFFFF)
++Size  17: 9,20    BAD  (FFHFHH)
++Size  18: 9,22    GOOD (HHFFFF)
++Size  19: 10,23   BAD  (FFHFHH)
++Size  20: 10,24   GOOD (HHFFFF)
++Size  21: 11,25   BAD  (FFHFHH)
++Size  22: 11,26   GOOD (HHFFFF)
++Size  23: 12,28   BAD  (FFHFHH)
++Size  24: 12,29   GOOD (HHFFFF)
++Size  25: 13,30   BAD  (FFHFHH)
++Size  26: 13,31   GOOD (HHFFFF)
++Size  27: 14,32   BAD  (FFHFHH)
++Size  28: 14,34   GOOD (HHFFFF)
++Size  29: 15,35   BAD  (FFHFHH)
++Size  30: 15,36   GOOD (HHFFFF)
++Size  31: 16,37   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,40   BAD  (FFHFHH)
++Size  34: 17,41   GOOD (HHFFFF)
++Size  35: 18,42   BAD  (FFHFHH)
++Size  36: 18,43   GOOD (HHFFFF)
++Size  37: 19,44   BAD  (FFHFHH)
++Size  38: 19,46   GOOD (HHFFFF)
++Size  39: 20,47   BAD  (FFHFHH)
++Size  40: 20,48   GOOD (HHFFFF)
++Size  41: 21,49   BAD  (FFHFHH)
++Size  42: 21,50   GOOD (HHFFFF)
++Size  43: 22,52   BAD  (FFHFHH)
++Size  44: 22,53   GOOD (HHFFFF)
++Size  45: 23,54   BAD  (FFHFHH)
++Size  46: 23,55   GOOD (HHFFFF)
++Size  47: 24,56   BAD  (FFHFHH)
++Size  48: 24,58   GOOD (HHFFFF)
++Size  49: 25,59   BAD  (FFHFHH)
++Size  50: 25,60   GOOD (HHFFFF)
++Size  51: 26,61   BAD  (FFHFHH)
++Size  52: 26,62   GOOD (HHFFFF)
++Size  53: 27,64   BAD  (FFHFHH)
++Size  54: 27,65   GOOD (HHFFFF)
++Size  55: 28,66   BAD  (FFHFHH)
++Size  56: 28,67   GOOD (HHFFFF)
++Size  57: 29,68   BAD  (FFHFHH)
++Size  58: 29,70   GOOD (HHFFFF)
++Size  59: 30,71   BAD  (FFHFHH)
++Size  60: 30,72   GOOD (HHFFFF)
++Size  61: 31,73   BAD  (FFHFHH)
++Size  62: 31,74   GOOD (HHFFFF)
++Size  63: 32,76   BAD  (FFHFHH)
++Size  64: 32,77   GOOD (HHFFFF)
++Size  65: 33,78   BAD  (FFHFHH)
++Size  66: 33,79   GOOD (HHFFFF)
++Size  67: 34,80   BAD  (FFHFHH)
++Size  68: 34,82   GOOD (HHFFFF)
++Size  69: 35,83   BAD  (FFHFHH)
++Size  70: 35,84   GOOD (HHFFFF)
++Size  71: 36,85   BAD  (FFHFHH)
++Size  72: 36,86   GOOD (HHFFFF)
++Size  73: 37,88   BAD  (FFHFHH)
++Size  74: 37,89   GOOD (HHFFFF)
++Size  75: 38,90   BAD  (FFHFHH)
++Size  76: 38,91   GOOD (HHFFFF)
++Size  77: 39,92   BAD  (FFHFHH)
++Size  78: 39,94   GOOD (HHFFFF)
++Size  79: 40,95   BAD  (FFHFHH)
++Size  80: 40,96   GOOD (HHFFFF)
++Size  81: 41,97   BAD  (FFHFHH)
++Size  82: 41,98   GOOD (HHFFFF)
++Size  83: 42,100  BAD  (FFHFHH)
++Size  84: 42,101  GOOD (HHFFFF)
++Size  85: 43,102  BAD  (FFHFHH)
++Size  86: 43,103  GOOD (HHFFFF)
++Size  87: 44,104  BAD  (FFHFHH)
++Size  88: 44,106  GOOD (HHFFFF)
++Size  89: 45,107  BAD  (FFHFHH)
++Size  90: 45,108  GOOD (HHFFFF)
++Size  91: 46,109  BAD  (FFHFHH)
++Size  92: 46,110  GOOD (HHFFFF)
++Size  93: 47,112  BAD  (FFHFHH)
++Size  94: 47,113  GOOD (HHFFFF)
++Size  95: 48,114  BAD  (FFHFHH)
++Size  96: 48,115  GOOD (HHFFFF)
++Size  97: 49,116  BAD  (FFHFHH)
++Size  98: 49,118  GOOD (HHFFFF)
++Size  99: 50,119  BAD  (FFHFHH)
++Size 100: 50,120  GOOD (HHFFFF)
++
++Windows 8
++---------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,4     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,10    GOOD (HHFFFF)
++Size   9: 5,11    BAD  (FFHFHH)
++Size  10: 5,12    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,16    BAD  (FFHFHH)
++Size  14: 7,17    GOOD (HHFFFF)
++Size  15: 8,18    BAD  (FFHFHH)
++Size  16: 8,19    GOOD (HHFFFF)
++Size  17: 9,20    BAD  (FFHFHH)
++Size  18: 9,22    GOOD (HHFFFF)
++Size  19: 10,23   BAD  (FFHFHH)
++Size  20: 10,24   GOOD (HHFFFF)
++Size  21: 11,25   BAD  (FFHFHH)
++Size  22: 11,26   GOOD (HHFFFF)
++Size  23: 12,28   BAD  (FFHFHH)
++Size  24: 12,29   GOOD (HHFFFF)
++Size  25: 13,30   BAD  (FFHFHH)
++Size  26: 13,31   GOOD (HHFFFF)
++Size  27: 14,32   BAD  (FFHFHH)
++Size  28: 14,34   GOOD (HHFFFF)
++Size  29: 15,35   BAD  (FFHFHH)
++Size  30: 15,36   GOOD (HHFFFF)
++Size  31: 16,37   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,40   BAD  (FFHFHH)
++Size  34: 17,41   GOOD (HHFFFF)
++Size  35: 18,42   BAD  (FFHFHH)
++Size  36: 18,43   GOOD (HHFFFF)
++Size  37: 19,44   BAD  (FFHFHH)
++Size  38: 19,46   GOOD (HHFFFF)
++Size  39: 20,47   BAD  (FFHFHH)
++Size  40: 20,48   GOOD (HHFFFF)
++Size  41: 21,49   BAD  (FFHFHH)
++Size  42: 21,50   GOOD (HHFFFF)
++Size  43: 22,52   BAD  (FFHFHH)
++Size  44: 22,53   GOOD (HHFFFF)
++Size  45: 23,54   BAD  (FFHFHH)
++Size  46: 23,55   GOOD (HHFFFF)
++Size  47: 24,56   BAD  (FFHFHH)
++Size  48: 24,58   GOOD (HHFFFF)
++Size  49: 25,59   BAD  (FFHFHH)
++Size  50: 25,60   GOOD (HHFFFF)
++Size  51: 26,61   BAD  (FFHFHH)
++Size  52: 26,62   GOOD (HHFFFF)
++Size  53: 27,64   BAD  (FFHFHH)
++Size  54: 27,65   GOOD (HHFFFF)
++Size  55: 28,66   BAD  (FFHFHH)
++Size  56: 28,67   GOOD (HHFFFF)
++Size  57: 29,68   BAD  (FFHFHH)
++Size  58: 29,70   GOOD (HHFFFF)
++Size  59: 30,71   BAD  (FFHFHH)
++Size  60: 30,72   GOOD (HHFFFF)
++Size  61: 31,73   BAD  (FFHFHH)
++Size  62: 31,74   GOOD (HHFFFF)
++Size  63: 32,76   BAD  (FFHFHH)
++Size  64: 32,77   GOOD (HHFFFF)
++Size  65: 33,78   BAD  (FFHFHH)
++Size  66: 33,79   GOOD (HHFFFF)
++Size  67: 34,80   BAD  (FFHFHH)
++Size  68: 34,82   GOOD (HHFFFF)
++Size  69: 35,83   BAD  (FFHFHH)
++Size  70: 35,84   GOOD (HHFFFF)
++Size  71: 36,85   BAD  (FFHFHH)
++Size  72: 36,86   GOOD (HHFFFF)
++Size  73: 37,88   BAD  (FFHFHH)
++Size  74: 37,89   GOOD (HHFFFF)
++Size  75: 38,90   BAD  (FFHFHH)
++Size  76: 38,91   GOOD (HHFFFF)
++Size  77: 39,92   BAD  (FFHFHH)
++Size  78: 39,94   GOOD (HHFFFF)
++Size  79: 40,95   BAD  (FFHFHH)
++Size  80: 40,96   GOOD (HHFFFF)
++Size  81: 41,97   BAD  (FFHFHH)
++Size  82: 41,98   GOOD (HHFFFF)
++Size  83: 42,100  BAD  (FFHFHH)
++Size  84: 42,101  GOOD (HHFFFF)
++Size  85: 43,102  BAD  (FFHFHH)
++Size  86: 43,103  GOOD (HHFFFF)
++Size  87: 44,104  BAD  (FFHFHH)
++Size  88: 44,106  GOOD (HHFFFF)
++Size  89: 45,107  BAD  (FFHFHH)
++Size  90: 45,108  GOOD (HHFFFF)
++Size  91: 46,109  BAD  (FFHFHH)
++Size  92: 46,110  GOOD (HHFFFF)
++Size  93: 47,112  BAD  (FFHFHH)
++Size  94: 47,113  GOOD (HHFFFF)
++Size  95: 48,114  BAD  (FFHFHH)
++Size  96: 48,115  GOOD (HHFFFF)
++Size  97: 49,116  BAD  (FFHFHH)
++Size  98: 49,118  GOOD (HHFFFF)
++Size  99: 50,119  BAD  (FFHFHH)
++Size 100: 50,120  GOOD (HHFFFF)
++
++Windows 8.1
++-----------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,4     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,10    GOOD (HHFFFF)
++Size   9: 5,11    BAD  (FFHFHH)
++Size  10: 5,12    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,16    BAD  (FFHFHH)
++Size  14: 7,17    GOOD (HHFFFF)
++Size  15: 8,18    BAD  (FFHFHH)
++Size  16: 8,19    GOOD (HHFFFF)
++Size  17: 9,20    BAD  (FFHFHH)
++Size  18: 9,22    GOOD (HHFFFF)
++Size  19: 10,23   BAD  (FFHFHH)
++Size  20: 10,24   GOOD (HHFFFF)
++Size  21: 11,25   BAD  (FFHFHH)
++Size  22: 11,26   GOOD (HHFFFF)
++Size  23: 12,28   BAD  (FFHFHH)
++Size  24: 12,29   GOOD (HHFFFF)
++Size  25: 13,30   BAD  (FFHFHH)
++Size  26: 13,31   GOOD (HHFFFF)
++Size  27: 14,32   BAD  (FFHFHH)
++Size  28: 14,34   GOOD (HHFFFF)
++Size  29: 15,35   BAD  (FFHFHH)
++Size  30: 15,36   GOOD (HHFFFF)
++Size  31: 16,37   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,40   BAD  (FFHFHH)
++Size  34: 17,41   GOOD (HHFFFF)
++Size  35: 18,42   BAD  (FFHFHH)
++Size  36: 18,43   GOOD (HHFFFF)
++Size  37: 19,44   BAD  (FFHFHH)
++Size  38: 19,46   GOOD (HHFFFF)
++Size  39: 20,47   BAD  (FFHFHH)
++Size  40: 20,48   GOOD (HHFFFF)
++Size  41: 21,49   BAD  (FFHFHH)
++Size  42: 21,50   GOOD (HHFFFF)
++Size  43: 22,52   BAD  (FFHFHH)
++Size  44: 22,53   GOOD (HHFFFF)
++Size  45: 23,54   BAD  (FFHFHH)
++Size  46: 23,55   GOOD (HHFFFF)
++Size  47: 24,56   BAD  (FFHFHH)
++Size  48: 24,58   GOOD (HHFFFF)
++Size  49: 25,59   BAD  (FFHFHH)
++Size  50: 25,60   GOOD (HHFFFF)
++Size  51: 26,61   BAD  (FFHFHH)
++Size  52: 26,62   GOOD (HHFFFF)
++Size  53: 27,64   BAD  (FFHFHH)
++Size  54: 27,65   GOOD (HHFFFF)
++Size  55: 28,66   BAD  (FFHFHH)
++Size  56: 28,67   GOOD (HHFFFF)
++Size  57: 29,68   BAD  (FFHFHH)
++Size  58: 29,70   GOOD (HHFFFF)
++Size  59: 30,71   BAD  (FFHFHH)
++Size  60: 30,72   GOOD (HHFFFF)
++Size  61: 31,73   BAD  (FFHFHH)
++Size  62: 31,74   GOOD (HHFFFF)
++Size  63: 32,76   BAD  (FFHFHH)
++Size  64: 32,77   GOOD (HHFFFF)
++Size  65: 33,78   BAD  (FFHFHH)
++Size  66: 33,79   GOOD (HHFFFF)
++Size  67: 34,80   BAD  (FFHFHH)
++Size  68: 34,82   GOOD (HHFFFF)
++Size  69: 35,83   BAD  (FFHFHH)
++Size  70: 35,84   GOOD (HHFFFF)
++Size  71: 36,85   BAD  (FFHFHH)
++Size  72: 36,86   GOOD (HHFFFF)
++Size  73: 37,88   BAD  (FFHFHH)
++Size  74: 37,89   GOOD (HHFFFF)
++Size  75: 38,90   BAD  (FFHFHH)
++Size  76: 38,91   GOOD (HHFFFF)
++Size  77: 39,92   BAD  (FFHFHH)
++Size  78: 39,94   GOOD (HHFFFF)
++Size  79: 40,95   BAD  (FFHFHH)
++Size  80: 40,96   GOOD (HHFFFF)
++Size  81: 41,97   BAD  (FFHFHH)
++Size  82: 41,98   GOOD (HHFFFF)
++Size  83: 42,100  BAD  (FFHFHH)
++Size  84: 42,101  GOOD (HHFFFF)
++Size  85: 43,102  BAD  (FFHFHH)
++Size  86: 43,103  GOOD (HHFFFF)
++Size  87: 44,104  BAD  (FFHFHH)
++Size  88: 44,106  GOOD (HHFFFF)
++Size  89: 45,107  BAD  (FFHFHH)
++Size  90: 45,108  GOOD (HHFFFF)
++Size  91: 46,109  BAD  (FFHFHH)
++Size  92: 46,110  GOOD (HHFFFF)
++Size  93: 47,112  BAD  (FFHFHH)
++Size  94: 47,113  GOOD (HHFFFF)
++Size  95: 48,114  BAD  (FFHFHH)
++Size  96: 48,115  GOOD (HHFFFF)
++Size  97: 49,116  BAD  (FFHFHH)
++Size  98: 49,118  GOOD (HHFFFF)
++Size  99: 50,119  BAD  (FFHFHH)
++Size 100: 50,120  GOOD (HHFFFF)
++
++Windows 10 14342 Old Console
++----------------------------
++
++Size   1: 1,2     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,4     BAD  (FFHFHH)
++Size   4: 2,5     GOOD (HHFFFF)
++Size   5: 3,6     BAD  (FFHFHH)
++Size   6: 3,7     GOOD (HHFFFF)
++Size   7: 4,8     BAD  (FFHFHH)
++Size   8: 4,10    GOOD (HHFFFF)
++Size   9: 5,11    BAD  (FFHFHH)
++Size  10: 5,12    GOOD (HHFFFF)
++Size  11: 6,13    BAD  (FFHFHH)
++Size  12: 6,14    GOOD (HHFFFF)
++Size  13: 7,16    BAD  (FFHFHH)
++Size  14: 7,17    GOOD (HHFFFF)
++Size  15: 8,18    BAD  (FFHFHH)
++Size  16: 8,19    GOOD (HHFFFF)
++Size  17: 9,20    BAD  (FFHFHH)
++Size  18: 9,22    GOOD (HHFFFF)
++Size  19: 10,23   BAD  (FFHFHH)
++Size  20: 10,24   GOOD (HHFFFF)
++Size  21: 11,25   BAD  (FFHFHH)
++Size  22: 11,26   GOOD (HHFFFF)
++Size  23: 12,28   BAD  (FFHFHH)
++Size  24: 12,29   GOOD (HHFFFF)
++Size  25: 13,30   BAD  (FFHFHH)
++Size  26: 13,31   GOOD (HHFFFF)
++Size  27: 14,32   BAD  (FFHFHH)
++Size  28: 14,34   GOOD (HHFFFF)
++Size  29: 15,35   BAD  (FFHFHH)
++Size  30: 15,36   GOOD (HHFFFF)
++Size  31: 16,37   BAD  (FFHFHH)
++Size  32: 16,38   GOOD (HHFFFF)
++Size  33: 17,40   BAD  (FFHFHH)
++Size  34: 17,41   GOOD (HHFFFF)
++Size  35: 18,42   BAD  (FFHFHH)
++Size  36: 18,43   GOOD (HHFFFF)
++Size  37: 19,44   BAD  (FFHFHH)
++Size  38: 19,46   GOOD (HHFFFF)
++Size  39: 20,47   BAD  (FFHFHH)
++Size  40: 20,48   GOOD (HHFFFF)
++Size  41: 21,49   BAD  (FFHFHH)
++Size  42: 21,50   GOOD (HHFFFF)
++Size  43: 22,52   BAD  (FFHFHH)
++Size  44: 22,53   GOOD (HHFFFF)
++Size  45: 23,54   BAD  (FFHFHH)
++Size  46: 23,55   GOOD (HHFFFF)
++Size  47: 24,56   BAD  (FFHFHH)
++Size  48: 24,58   GOOD (HHFFFF)
++Size  49: 25,59   BAD  (FFHFHH)
++Size  50: 25,60   GOOD (HHFFFF)
++Size  51: 26,61   BAD  (FFHFHH)
++Size  52: 26,62   GOOD (HHFFFF)
++Size  53: 27,64   BAD  (FFHFHH)
++Size  54: 27,65   GOOD (HHFFFF)
++Size  55: 28,66   BAD  (FFHFHH)
++Size  56: 28,67   GOOD (HHFFFF)
++Size  57: 29,68   BAD  (FFHFHH)
++Size  58: 29,70   GOOD (HHFFFF)
++Size  59: 30,71   BAD  (FFHFHH)
++Size  60: 30,72   GOOD (HHFFFF)
++Size  61: 31,73   BAD  (FFHFHH)
++Size  62: 31,74   GOOD (HHFFFF)
++Size  63: 32,76   BAD  (FFHFHH)
++Size  64: 32,77   GOOD (HHFFFF)
++Size  65: 33,78   BAD  (FFHFHH)
++Size  66: 33,79   GOOD (HHFFFF)
++Size  67: 34,80   BAD  (FFHFHH)
++Size  68: 34,82   GOOD (HHFFFF)
++Size  69: 35,83   BAD  (FFHFHH)
++Size  70: 35,84   GOOD (HHFFFF)
++Size  71: 36,85   BAD  (FFHFHH)
++Size  72: 36,86   GOOD (HHFFFF)
++Size  73: 37,88   BAD  (FFHFHH)
++Size  74: 37,89   GOOD (HHFFFF)
++Size  75: 38,90   BAD  (FFHFHH)
++Size  76: 38,91   GOOD (HHFFFF)
++Size  77: 39,92   BAD  (FFHFHH)
++Size  78: 39,94   GOOD (HHFFFF)
++Size  79: 40,95   BAD  (FFHFHH)
++Size  80: 40,96   GOOD (HHFFFF)
++Size  81: 41,97   BAD  (FFHFHH)
++Size  82: 41,98   GOOD (HHFFFF)
++Size  83: 42,100  BAD  (FFHFHH)
++Size  84: 42,101  GOOD (HHFFFF)
++Size  85: 43,102  BAD  (FFHFHH)
++Size  86: 43,103  GOOD (HHFFFF)
++Size  87: 44,104  BAD  (FFHFHH)
++Size  88: 44,106  GOOD (HHFFFF)
++Size  89: 45,107  BAD  (FFHFHH)
++Size  90: 45,108  GOOD (HHFFFF)
++Size  91: 46,109  BAD  (FFHFHH)
++Size  92: 46,110  GOOD (HHFFFF)
++Size  93: 47,112  BAD  (FFHFHH)
++Size  94: 47,113  GOOD (HHFFFF)
++Size  95: 48,114  BAD  (FFHFHH)
++Size  96: 48,115  GOOD (HHFFFF)
++Size  97: 49,116  BAD  (FFHFHH)
++Size  98: 49,118  GOOD (HHFFFF)
++Size  99: 50,119  BAD  (FFHFHH)
++Size 100: 50,120  GOOD (HHFFFF)
++
++Windows 10 14342 New Console
++----------------------------
++
++Size   1: 1,1     GOOD (HHFFFF)
++Size   2: 1,2     GOOD (HHFFFF)
++Size   3: 2,3     GOOD (HHFFFF)
++Size   4: 2,4     GOOD (HHFFFF)
++Size   5: 3,5     GOOD (HHFFFF)
++Size   6: 3,6     GOOD (HHFFFF)
++Size   7: 4,7     GOOD (HHFFFF)
++Size   8: 4,8     GOOD (HHFFFF)
++Size   9: 5,9     GOOD (HHFFFF)
++Size  10: 5,10    GOOD (HHFFFF)
++Size  11: 6,11    GOOD (HHFFFF)
++Size  12: 6,12    GOOD (HHFFFF)
++Size  13: 7,13    GOOD (HHFFFF)
++Size  14: 7,14    GOOD (HHFFFF)
++Size  15: 8,15    GOOD (HHFFFF)
++Size  16: 8,16    GOOD (HHFFFF)
++Size  17: 9,17    GOOD (HHFFFF)
++Size  18: 9,18    GOOD (HHFFFF)
++Size  19: 10,19   GOOD (HHFFFF)
++Size  20: 10,20   GOOD (HHFFFF)
++Size  21: 11,21   GOOD (HHFFFF)
++Size  22: 11,22   GOOD (HHFFFF)
++Size  23: 12,23   GOOD (HHFFFF)
++Size  24: 12,24   GOOD (HHFFFF)
++Size  25: 13,25   GOOD (HHFFFF)
++Size  26: 13,26   GOOD (HHFFFF)
++Size  27: 14,27   GOOD (HHFFFF)
++Size  28: 14,28   GOOD (HHFFFF)
++Size  29: 15,29   GOOD (HHFFFF)
++Size  30: 15,30   GOOD (HHFFFF)
++Size  31: 16,31   GOOD (HHFFFF)
++Size  32: 16,32   GOOD (HHFFFF)
++Size  33: 17,33   GOOD (HHFFFF)
++Size  34: 17,34   GOOD (HHFFFF)
++Size  35: 18,35   GOOD (HHFFFF)
++Size  36: 18,36   GOOD (HHFFFF)
++Size  37: 19,37   GOOD (HHFFFF)
++Size  38: 19,38   GOOD (HHFFFF)
++Size  39: 20,39   GOOD (HHFFFF)
++Size  40: 20,40   GOOD (HHFFFF)
++Size  41: 21,41   GOOD (HHFFFF)
++Size  42: 21,42   GOOD (HHFFFF)
++Size  43: 22,43   GOOD (HHFFFF)
++Size  44: 22,44   GOOD (HHFFFF)
++Size  45: 23,45   GOOD (HHFFFF)
++Size  46: 23,46   GOOD (HHFFFF)
++Size  47: 24,47   GOOD (HHFFFF)
++Size  48: 24,48   GOOD (HHFFFF)
++Size  49: 25,49   GOOD (HHFFFF)
++Size  50: 25,50   GOOD (HHFFFF)
++Size  51: 26,51   GOOD (HHFFFF)
++Size  52: 26,52   GOOD (HHFFFF)
++Size  53: 27,53   GOOD (HHFFFF)
++Size  54: 27,54   GOOD (HHFFFF)
++Size  55: 28,55   GOOD (HHFFFF)
++Size  56: 28,56   GOOD (HHFFFF)
++Size  57: 29,57   GOOD (HHFFFF)
++Size  58: 29,58   GOOD (HHFFFF)
++Size  59: 30,59   GOOD (HHFFFF)
++Size  60: 30,60   GOOD (HHFFFF)
++Size  61: 31,61   GOOD (HHFFFF)
++Size  62: 31,62   GOOD (HHFFFF)
++Size  63: 32,63   GOOD (HHFFFF)
++Size  64: 32,64   GOOD (HHFFFF)
++Size  65: 33,65   GOOD (HHFFFF)
++Size  66: 33,66   GOOD (HHFFFF)
++Size  67: 34,67   GOOD (HHFFFF)
++Size  68: 34,68   GOOD (HHFFFF)
++Size  69: 35,69   GOOD (HHFFFF)
++Size  70: 35,70   GOOD (HHFFFF)
++Size  71: 36,71   GOOD (HHFFFF)
++Size  72: 36,72   GOOD (HHFFFF)
++Size  73: 37,73   GOOD (HHFFFF)
++Size  74: 37,74   GOOD (HHFFFF)
++Size  75: 38,75   GOOD (HHFFFF)
++Size  76: 38,76   GOOD (HHFFFF)
++Size  77: 39,77   GOOD (HHFFFF)
++Size  78: 39,78   GOOD (HHFFFF)
++Size  79: 40,79   GOOD (HHFFFF)
++Size  80: 40,80   GOOD (HHFFFF)
++Size  81: 41,81   GOOD (HHFFFF)
++Size  82: 41,82   GOOD (HHFFFF)
++Size  83: 42,83   GOOD (HHFFFF)
++Size  84: 42,84   GOOD (HHFFFF)
++Size  85: 43,85   GOOD (HHFFFF)
++Size  86: 43,86   GOOD (HHFFFF)
++Size  87: 44,87   GOOD (HHFFFF)
++Size  88: 44,88   GOOD (HHFFFF)
++Size  89: 45,89   GOOD (HHFFFF)
++Size  90: 45,90   GOOD (HHFFFF)
++Size  91: 46,91   GOOD (HHFFFF)
++Size  92: 46,92   GOOD (HHFFFF)
++Size  93: 47,93   GOOD (HHFFFF)
++Size  94: 47,94   GOOD (HHFFFF)
++Size  95: 48,95   GOOD (HHFFFF)
++Size  96: 48,96   GOOD (HHFFFF)
++Size  97: 49,97   GOOD (HHFFFF)
++Size  98: 49,98   GOOD (HHFFFF)
++Size  99: 50,99   GOOD (HHFFFF)
++Size 100: 50,100  GOOD (HHFFFF)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d5261d8db3968f9914732c7c13ad3300135f6bf3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,16 @@@
++The narrowest allowed console window, in pixels, on a conventional (~96dpi)
++monitor:
++
++(mode con: cols=40 lines=40) && SetFont.exe -face "Lucida Console" -h 1 && (ping -n 4 127.0.0.1 > NUL) && cls && GetConsolePos.exe && SetFont.exe -face "Lucida Console" -h 12
++
++(mode con: cols=40 lines=40) && SetFont.exe -face "Lucida Console" -h 16 && (ping -n 4 127.0.0.1 > NUL) && cls && GetConsolePos.exe && SetFont.exe -face "Lucida Console" -h 12
++
++                sz1:px      sz1:col     sz16:px     sz16:col
++Vista:          124         104         137         10
++Windows 7:      132         112         147         11
++Windows 8:      140         120         147         11
++Windows 8.1:    140         120         147         11
++Windows 10 OLD: 136         116         147         11
++Windows 10 NEW: 136         103         136         10
++
++I used build 14342 to test Windows 10.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..15a825cb51b21b8fc9666542b80e6a21f557d21c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,4 @@@
++As before, avoid odd sizes in favor of even sizes.
++
++It's curious that the Japanese font is handled so poorly, especially with
++Windows 8 and later.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..fef397a1e34fe32ecf286758fc6541f1108974f6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,144 @@@
++Issues:
++
++ - Starting with the 14342 build, changing the font using
++   SetCurrentConsoleFontEx does not affect the window size.  e.g. The content
++   itself will resize/redraw, but the window neither shrinks nor expands.
++   Presumably this is an oversight?  It's almost a convenience; if a program
++   is going to resize the window anyway, then it's nice that the window size
++   contraints don't get in the way.  Ordinarily, changing the font doesn't just
++   change the window size in pixels--it can also change the size as measured in
++   rows and columns.
++
++ - (Aside: in the 14342 build, there is also a bug with wmic.exe.  Open a console
++   with more than 300 lines of screen buffer, then fill those lines with, e.g.,
++   dir /s.  Then run wmic.exe.  You won't be able to see the wmic.exe prompt.
++   If you query the screen buffer info somehow, you'll notice that the srWindow
++   is not contained within the dwSize.  This breaks winpty's scraping, because
++   it's invalid.)
++
++ - In build 14316, with the Japanese locale, with the 437 code page, attempting
++   to set the Consolas font instead sets the Terminal (raster) font.  It seems
++   to pick an appropriate vertical size.
++
++ - It seems necessary to specify "-family 0x36" for maximum reliability.
++   Setting the family to 0 almost always works, and specifying just -tt rarely
++   works.
++
++Win7
++    English locale / 437 code page:
++        SetFont.exe -face Consolas -h 16                    works
++        SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++        SetFont.exe -face Consolas -h 16 -family 0x36       works
++    Japanese locale / 932 code page:
++        SetFont.exe -face Consolas -h 16                    works
++        SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++        SetFont.exe -face Consolas -h 16 -family 0x36       works
++    Japanese locale / 437 code page:
++        SetFont.exe -face Consolas -h 16                    works
++        SetFont.exe -face Consolas -h 16 -tt                unreliable
++        SetFont.exe -face Consolas -h 16 -family 0x36       works
++
++Win10 Build 10586
++    New console
++        Japanese locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++
++Win10 Build 14316
++    Old console
++        English locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++        Japanese locale / 932 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++        Japanese locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selected very small Consolas font
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++    New console
++        English locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                works
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++        Japanese locale / 932 code page:
++            SetFont.exe -face Consolas -h 16                    selects gothic instead
++            SetFont.exe -face Consolas -h 16 -tt                selects gothic instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       selects gothic instead
++        Japanese locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -family 0x36(*)    selects Terminal font instead
++
++Win10 Build 14342
++    Old Console
++        English locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++        Japanese locale / 932 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++        Japanese locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++    New console
++        English locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    works
++            SetFont.exe -face Consolas -h 16 -tt                works
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++        Japanese locale / 932 code page:
++            SetFont.exe -face Consolas -h 16                    selects gothic instead
++            SetFont.exe -face Consolas -h 16 -tt                selects gothic instead
++            SetFont.exe -face Consolas -h 16 -family 0x36       selects gothic instead
++        Japanese locale / 437 code page:
++            SetFont.exe -face Consolas -h 16                    selects Terminal font instead
++            SetFont.exe -face Consolas -h 16 -tt                works
++            SetFont.exe -face Consolas -h 16 -family 0x36       works
++
++(*) I was trying to figure out whether the inconsistency was at when I stumbled
++onto this completely unexpected bug.  Here's more detail:
++
++    F:\>SetFont.exe -face Consolas -h 16 -family 0x36 -weight normal -w 8
++    Setting to: nFont=0 dwFontSize=(8,16) FontFamily=0x36 FontWeight=400 FaceName="Consolas"
++    SetCurrentConsoleFontEx returned 1
++
++    F:\>GetFont.exe
++    largestConsoleWindowSize=(96,50)
++    maxWnd=0: nFont=0 dwFontSize=(12,16) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
++    maxWnd=1: nFont=0 dwFontSize=(96,25) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
++    00-00: 12x16
++    GetNumberOfConsoleFonts returned 0
++    CP=437 OutputCP=437
++
++    F:\>SetFont.exe -face "Lucida Console" -h 16 -family 0x36 -weight normal
++    Setting to: nFont=0 dwFontSize=(0,16) FontFamily=0x36 FontWeight=400 FaceName="Lucida Console"
++    SetCurrentConsoleFontEx returned 1
++
++    F:\>GetFont.exe
++    largestConsoleWindowSize=(96,50)
++    maxWnd=0: nFont=0 dwFontSize=(12,16) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
++    maxWnd=1: nFont=0 dwFontSize=(96,25) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
++    00-00: 12x16
++    GetNumberOfConsoleFonts returned 0
++    CP=437 OutputCP=437
++
++    F:\>SetFont.exe -face "Lucida Console" -h 12 -family 0x36 -weight normal
++    Setting to: nFont=0 dwFontSize=(0,12) FontFamily=0x36 FontWeight=400 FaceName="Lucida Console"
++    SetCurrentConsoleFontEx returned 1
++
++    F:\>GetFont.exe
++    largestConsoleWindowSize=(230,66)
++    maxWnd=0: nFont=0 dwFontSize=(5,12) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
++    maxWnd=1: nFont=0 dwFontSize=(116,36) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
++    00-00:  5x12
++    GetNumberOfConsoleFonts returned 0
++    CP=437 OutputCP=437
++
++Even attempting to set to a Lucida Console / Consolas font from the Console
++properties dialog fails.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..254bcc81a60c4dfebd384dccc7eaf62602fd69b3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,100 @@@
++#include <windows.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include <vector>
++
++#include "TestUtil.cc"
++
++#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0]))
++
++// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
++const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // Japanese
++const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // Simplified Chinese
++const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // Traditional Chinese
++const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // Korean
++
++std::vector<bool> condense(const std::vector<CHAR_INFO> &buf) {
++    std::vector<bool> ret;
++    size_t i = 0;
++    while (i < buf.size()) {
++        if (buf[i].Char.UnicodeChar == L' ' &&
++                ((buf[i].Attributes & 0x300) == 0)) {
++            // end of line
++            break;
++        } else if (i + 1 < buf.size() &&
++                ((buf[i].Attributes & 0x300) == 0x100) &&
++                ((buf[i + 1].Attributes & 0x300) == 0x200) &&
++                buf[i].Char.UnicodeChar != L' ' &&
++                buf[i].Char.UnicodeChar == buf[i + 1].Char.UnicodeChar) {
++            // double-width
++            ret.push_back(true);
++            i += 2;
++        } else if ((buf[i].Attributes & 0x300) == 0) {
++            // single-width
++            ret.push_back(false);
++            i++;
++        } else {
++            ASSERT(false && "unexpected output");
++        }
++    }
++    return ret;
++}
++
++int main(int argc, char *argv[]) {
++    if (argc != 2) {
++        printf("Usage: %s \"arguments for SetFont.exe\"\n", argv[0]);
++        return 1;
++    }
++
++    const char *setFontArgs = argv[1];
++
++    const wchar_t testLine[] = { 0xA2, 0xA3, 0x2014, 0x3044, 0x30FC, 0x4000, 0 };
++    const HANDLE conout = openConout();
++
++    char setFontCmd[1024];
++    for (int h = 1; h <= 100; ++h) {
++        sprintf(setFontCmd, ".\\SetFont.exe %s -h %d && cls", setFontArgs, h);
++        system(setFontCmd);
++
++        CONSOLE_FONT_INFOEX infoex = {};
++        infoex.cbSize = sizeof(infoex);
++        BOOL success = GetCurrentConsoleFontEx(conout, FALSE, &infoex);
++        ASSERT(success && "GetCurrentConsoleFontEx failed");
++
++        DWORD actual = 0;
++        success = WriteConsoleW(conout, testLine, wcslen(testLine), &actual, nullptr);
++        ASSERT(success && actual == wcslen(testLine));
++
++        std::vector<CHAR_INFO> readBuf(14);
++        const SMALL_RECT readRegion = {0, 0, static_cast<short>(readBuf.size() - 1), 0};
++        SMALL_RECT readRegion2 = readRegion;
++        success = ReadConsoleOutputW(
++            conout, readBuf.data(), 
++            {static_cast<short>(readBuf.size()), 1}, 
++            {0, 0},
++            &readRegion2);
++        ASSERT(success && !memcmp(&readRegion, &readRegion2, sizeof(readRegion)));
++
++        const auto widths = condense(readBuf);
++        std::string widthsStr;
++        for (bool width : widths) {
++            widthsStr.append(width ? "F" : "H");
++        }
++        char size[16];
++        sprintf(size, "%d,%d", infoex.dwFontSize.X, infoex.dwFontSize.Y);
++        const char *status = "";
++        if (widthsStr == "HHFFFF") {
++            status = "GOOD";
++        } else if (widthsStr == "HHHFFF") {
++            status = "OK";
++        } else {
++            status = "BAD";
++        }
++        trace("Size %3d: %-7s %-4s (%s)", h, size, status, widthsStr.c_str());
++    }
++    sprintf(setFontCmd, ".\\SetFont.exe %s -h 14", setFontArgs);
++    system(setFontCmd);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..aade488f9e26b23ea15e9d3730ba818f8aab1c7c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,21 @@@
++#include <ctype.h>
++#include <stdio.h>
++#include <string.h>
++
++static inline void formatChar(char *str, char ch)
++{
++    // Print some common control codes.
++    switch (ch) {
++    case '\r': strcpy(str, "CR "); break;
++    case '\n': strcpy(str, "LF "); break;
++    case ' ':  strcpy(str, "SP "); break;
++    case 27:   strcpy(str, "^[ "); break;
++    case 3:    strcpy(str, "^C "); break;
++    default:
++        if (isgraph(ch))
++            sprintf(str, "%c ", ch);
++        else
++            sprintf(str, "%02x ", ch);
++        break;
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2c0b0086a14d5d2cd6c8bb9f05fb26761654796c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,62 @@@
++#include <windows.h>
++
++#include "TestUtil.cc"
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
++
++int main(int argc, char *argv[0]) {
++
++    if (argc != 2) {
++        printf("Usage: %s (mark|selectall|read)\n", argv[0]);
++        return 1;
++    }
++
++    enum class Test { Mark, SelectAll, Read } test;
++    if (!strcmp(argv[1], "mark")) {
++        test = Test::Mark;
++    } else if (!strcmp(argv[1], "selectall")) {
++        test = Test::SelectAll;
++    } else if (!strcmp(argv[1], "read")) {
++        test = Test::Read;
++    } else {
++        printf("Invalid test: %s\n", argv[1]);
++        return 1;
++    }
++
++    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++    TimeMeasurement tm;
++    HWND hwnd = GetConsoleWindow();
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(100, 3000);
++    system("cls");
++    setWindowPos(0, 2975, 100, 25);
++    setCursorPos(0, 2999);
++
++    ShowWindow(hwnd, SW_HIDE);
++
++    for (int i = 0; i < 1000; ++i) {
++        // CONSOLE_SCREEN_BUFFER_INFO info = {};
++        // GetConsoleScreenBufferInfo(conout, &info);
++
++        if (test == Test::Mark) {
++            SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
++            SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
++        } else if (test == Test::SelectAll) {
++            SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0);
++            SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
++        } else if (test == Test::Read) {
++            static CHAR_INFO buffer[100 * 3000];
++            const SMALL_RECT readRegion = {0, 0, 99, 2999};
++            SMALL_RECT tmp = readRegion;
++            BOOL ret = ReadConsoleOutput(conout, buffer, {100, 3000}, {0, 0}, &tmp);
++            ASSERT(ret && !memcmp(&tmp, &readRegion, sizeof(tmp)));
++        }
++    }
++
++    ShowWindow(hwnd, SW_SHOW);
++
++    printf("elapsed: %f\n", tm.elapsed());
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cd6ed1943adbd22f87a7d0faf34aba0faa0916f6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,20 @@@
++#include <conio.h>
++#include <ctype.h>
++#include <stdio.h>
++
++int main() {
++    printf("\nPress any keys -- Ctrl-D exits\n\n");
++
++    while (true) {
++        const int ch = getch();
++        printf("0x%x", ch);
++        if (isgraph(ch)) {
++            printf(" '%c'", ch);
++        }
++        printf("\n");
++        if (ch == 0x4) { // Ctrl-D
++            break;
++        }
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1f3cc5316f118da485446caa4d59ad71b1900355
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,41 @@@
++#include <windows.h>
++
++#include <stdio.h>
++
++#include "TestUtil.cc"
++
++int main() {
++    const HANDLE conout = openConout();
++
++    CONSOLE_SCREEN_BUFFER_INFO info = {};
++    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
++    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
++
++    trace("cursor=%d,%d", info.dwCursorPosition.X, info.dwCursorPosition.Y);
++    printf("cursor=%d,%d\n", info.dwCursorPosition.X, info.dwCursorPosition.Y);
++
++    trace("srWindow={L=%d,T=%d,R=%d,B=%d}", info.srWindow.Left, info.srWindow.Top, info.srWindow.Right, info.srWindow.Bottom);
++    printf("srWindow={L=%d,T=%d,R=%d,B=%d}\n", info.srWindow.Left, info.srWindow.Top, info.srWindow.Right, info.srWindow.Bottom);
++
++    trace("dwSize=%d,%d", info.dwSize.X, info.dwSize.Y);
++    printf("dwSize=%d,%d\n", info.dwSize.X, info.dwSize.Y);
++
++    const HWND hwnd = GetConsoleWindow();
++    if (hwnd != NULL) {
++        RECT r = {};
++        if (GetWindowRect(hwnd, &r)) {
++            const int w = r.right - r.left;
++            const int h = r.bottom - r.top;
++            trace("hwnd: pos=(%d,%d) size=(%d,%d)", r.left, r.top, w, h);
++            printf("hwnd: pos=(%d,%d) size=(%d,%d)\n", r.left, r.top, w, h);
++        } else {
++            trace("GetWindowRect failed");
++            printf("GetWindowRect failed\n");
++        }
++    } else {
++        trace("GetConsoleWindow returned NULL");
++        printf("GetConsoleWindow returned NULL\n");
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..38625317ab255ba6cd1e3b29fafc584047cfb6ea
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,261 @@@
++#include <windows.h>
++#include <stdio.h>
++#include <stdarg.h>
++#include <wchar.h>
++
++#include "../src/shared/OsModule.h"
++#include "../src/shared/StringUtil.h"
++
++#include "TestUtil.cc"
++#include "../src/shared/StringUtil.cc"
++
++#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
++
++// Some of these types and functions are missing from the MinGW headers.
++// Others are undocumented.
++
++struct AGENT_CONSOLE_FONT_INFO {
++    DWORD nFont;
++    COORD dwFontSize;
++};
++
++struct AGENT_CONSOLE_FONT_INFOEX {
++    ULONG cbSize;
++    DWORD nFont;
++    COORD dwFontSize;
++    UINT FontFamily;
++    UINT FontWeight;
++    WCHAR FaceName[LF_FACESIZE];
++};
++
++// undocumented XP API
++typedef BOOL WINAPI SetConsoleFont_t(
++            HANDLE hOutput,
++            DWORD dwFontIndex);
++
++// undocumented XP API
++typedef DWORD WINAPI GetNumberOfConsoleFonts_t();
++
++// XP and up
++typedef BOOL WINAPI GetCurrentConsoleFont_t(
++            HANDLE hOutput,
++            BOOL bMaximumWindow,
++            AGENT_CONSOLE_FONT_INFO *lpConsoleCurrentFont);
++
++// XP and up
++typedef COORD WINAPI GetConsoleFontSize_t(
++            HANDLE hConsoleOutput,
++            DWORD nFont);
++
++// Vista and up
++typedef BOOL WINAPI GetCurrentConsoleFontEx_t(
++            HANDLE hConsoleOutput,
++            BOOL bMaximumWindow,
++            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
++
++// Vista and up
++typedef BOOL WINAPI SetCurrentConsoleFontEx_t(
++            HANDLE hConsoleOutput,
++            BOOL bMaximumWindow,
++            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
++
++#define GET_MODULE_PROC(mod, funcName) \
++    m_##funcName = reinterpret_cast<funcName##_t*>((mod).proc(#funcName)); \
++
++#define DEFINE_ACCESSOR(funcName) \
++    funcName##_t &funcName() const { \
++        ASSERT(valid()); \
++        return *m_##funcName; \
++    }
++
++class XPFontAPI {
++public:
++    XPFontAPI() : m_kernel32(L"kernel32.dll") {
++        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFont);
++        GET_MODULE_PROC(m_kernel32, GetConsoleFontSize);
++    }
++
++    bool valid() const {
++        return m_GetCurrentConsoleFont != NULL &&
++            m_GetConsoleFontSize != NULL;
++    }
++
++    DEFINE_ACCESSOR(GetCurrentConsoleFont)
++    DEFINE_ACCESSOR(GetConsoleFontSize)
++
++private:
++    OsModule m_kernel32;
++    GetCurrentConsoleFont_t *m_GetCurrentConsoleFont;
++    GetConsoleFontSize_t *m_GetConsoleFontSize;
++};
++
++class UndocumentedXPFontAPI : public XPFontAPI {
++public:
++    UndocumentedXPFontAPI() : m_kernel32(L"kernel32.dll") {
++        GET_MODULE_PROC(m_kernel32, SetConsoleFont);
++        GET_MODULE_PROC(m_kernel32, GetNumberOfConsoleFonts);
++    }
++
++    bool valid() const {
++        return this->XPFontAPI::valid() &&
++            m_SetConsoleFont != NULL &&
++            m_GetNumberOfConsoleFonts != NULL;
++    }
++
++    DEFINE_ACCESSOR(SetConsoleFont)
++    DEFINE_ACCESSOR(GetNumberOfConsoleFonts)
++
++private:
++    OsModule m_kernel32;
++    SetConsoleFont_t *m_SetConsoleFont;
++    GetNumberOfConsoleFonts_t *m_GetNumberOfConsoleFonts;
++};
++
++class VistaFontAPI : public XPFontAPI {
++public:
++    VistaFontAPI() : m_kernel32(L"kernel32.dll") {
++        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFontEx);
++        GET_MODULE_PROC(m_kernel32, SetCurrentConsoleFontEx);
++    }
++
++    bool valid() const {
++        return this->XPFontAPI::valid() &&
++            m_GetCurrentConsoleFontEx != NULL &&
++            m_SetCurrentConsoleFontEx != NULL;
++    }
++
++    DEFINE_ACCESSOR(GetCurrentConsoleFontEx)
++    DEFINE_ACCESSOR(SetCurrentConsoleFontEx)
++
++private:
++    OsModule m_kernel32;
++    GetCurrentConsoleFontEx_t *m_GetCurrentConsoleFontEx;
++    SetCurrentConsoleFontEx_t *m_SetCurrentConsoleFontEx;
++};
++
++static std::vector<std::pair<DWORD, COORD> > readFontTable(
++        XPFontAPI &api, HANDLE conout, DWORD maxCount) {
++    std::vector<std::pair<DWORD, COORD> > ret;
++    for (DWORD i = 0; i < maxCount; ++i) {
++        COORD size = api.GetConsoleFontSize()(conout, i);
++        if (size.X == 0 && size.Y == 0) {
++            break;
++        }
++        ret.push_back(std::make_pair(i, size));
++    }
++    return ret;
++}
++
++static void dumpFontTable(HANDLE conout) {
++    const int kMaxCount = 1000;
++    XPFontAPI api;
++    if (!api.valid()) {
++        printf("dumpFontTable: cannot dump font table -- missing APIs\n");
++        return;
++    }
++    std::vector<std::pair<DWORD, COORD> > table =
++        readFontTable(api, conout, kMaxCount);
++    std::string line;
++    char tmp[128];
++    size_t first = 0;
++    while (first < table.size()) {
++        size_t last = std::min(table.size() - 1, first + 10 - 1);
++        winpty_snprintf(tmp, "%02u-%02u:",
++            static_cast<unsigned>(first), static_cast<unsigned>(last));
++        line = tmp;
++        for (size_t i = first; i <= last; ++i) {
++            if (i % 10 == 5) {
++                line += "  - ";
++            }
++            winpty_snprintf(tmp, " %2dx%-2d",
++                table[i].second.X, table[i].second.Y);
++            line += tmp;
++        }
++        printf("%s\n", line.c_str());
++        first = last + 1;
++    }
++    if (table.size() == kMaxCount) {
++        printf("... stopped reading at %d fonts ...\n", kMaxCount);
++    }
++}
++
++static std::string stringToCodePoints(const std::wstring &str) {
++    std::string ret = "(";
++    for (size_t i = 0; i < str.size(); ++i) {
++        char tmp[32];
++        winpty_snprintf(tmp, "%X", str[i]);
++        if (ret.size() > 1) {
++            ret.push_back(' ');
++        }
++        ret += tmp;
++    }
++    ret.push_back(')');
++    return ret;
++}
++
++static void dumpFontInfoEx(
++        const AGENT_CONSOLE_FONT_INFOEX &infoex) {
++    std::wstring faceName(infoex.FaceName,
++        winpty_wcsnlen(infoex.FaceName, COUNT_OF(infoex.FaceName)));
++    cprintf(L"nFont=%u dwFontSize=(%d,%d) "
++        "FontFamily=0x%x FontWeight=%u FaceName=%ls %hs\n",
++        static_cast<unsigned>(infoex.nFont),
++        infoex.dwFontSize.X, infoex.dwFontSize.Y,
++        infoex.FontFamily, infoex.FontWeight, faceName.c_str(),
++        stringToCodePoints(faceName).c_str());
++}
++
++static void dumpVistaFont(VistaFontAPI &api, HANDLE conout, BOOL maxWindow) {
++    AGENT_CONSOLE_FONT_INFOEX infoex = {0};
++    infoex.cbSize = sizeof(infoex);
++    if (!api.GetCurrentConsoleFontEx()(conout, maxWindow, &infoex)) {
++        printf("GetCurrentConsoleFontEx call failed\n");
++        return;
++    }
++    dumpFontInfoEx(infoex);
++}
++
++static void dumpXPFont(XPFontAPI &api, HANDLE conout, BOOL maxWindow) {
++    AGENT_CONSOLE_FONT_INFO info = {0};
++    if (!api.GetCurrentConsoleFont()(conout, maxWindow, &info)) {
++        printf("GetCurrentConsoleFont call failed\n");
++        return;
++    }
++    printf("nFont=%u dwFontSize=(%d,%d)\n",
++        static_cast<unsigned>(info.nFont),
++        info.dwFontSize.X, info.dwFontSize.Y);
++}
++
++static void dumpFontAndTable(HANDLE conout) {
++    VistaFontAPI vista;
++    if (vista.valid()) {
++        printf("maxWnd=0: "); dumpVistaFont(vista, conout, FALSE);
++        printf("maxWnd=1: "); dumpVistaFont(vista, conout, TRUE);
++        dumpFontTable(conout);
++        return;
++    }
++    UndocumentedXPFontAPI xp;
++    if (xp.valid()) {
++        printf("maxWnd=0: "); dumpXPFont(xp, conout, FALSE);
++        printf("maxWnd=1: "); dumpXPFont(xp, conout, TRUE);
++        dumpFontTable(conout);
++        return;
++    }
++    printf("setSmallFont: neither Vista nor XP APIs detected -- giving up\n");
++    dumpFontTable(conout);
++}
++
++int main() {
++    const HANDLE conout = openConout();
++    const COORD largest = GetLargestConsoleWindowSize(conout);
++    printf("largestConsoleWindowSize=(%d,%d)\n", largest.X, largest.Y);
++    dumpFontAndTable(conout);
++    UndocumentedXPFontAPI xp;
++    if (xp.valid()) {
++        printf("GetNumberOfConsoleFonts returned %u\n", xp.GetNumberOfConsoleFonts()());
++    } else {
++        printf("The GetNumberOfConsoleFonts API was missing\n");
++    }
++    printf("CP=%u OutputCP=%u\n", GetConsoleCP(), GetConsoleOutputCP());
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0c488597bd2592a8c05065910e8eb619b800cc1f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,51 @@@
++#
++# Usage: powershell <path>\IdentifyConsoleWindow.ps1
++#
++# This script determines whether the process has a console attached, whether
++# that console has a non-NULL window (e.g. HWND), and whether the window is on
++# the current window station.
++#
++
++$signature = @'
++[DllImport("kernel32.dll", SetLastError=true)]
++public static extern IntPtr GetConsoleWindow();
++
++[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
++public static extern bool SetConsoleTitle(String title);
++
++[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
++public static extern int GetWindowText(IntPtr hWnd,
++                                       System.Text.StringBuilder lpString,
++                                       int nMaxCount);
++'@
++
++$WinAPI = Add-Type -MemberDefinition $signature `
++    -Name WinAPI -Namespace IdentifyConsoleWindow -PassThru
++
++if (!$WinAPI::SetConsoleTitle("ConsoleWindowScript")) {
++    echo "error: could not change console title -- is a console attached?"
++    exit 1
++} else {
++    echo "note: successfully set console title to ""ConsoleWindowScript""."
++}
++
++$hwnd = $WinAPI::GetConsoleWindow()
++if ($hwnd -eq 0) {
++    echo "note: GetConsoleWindow returned NULL."
++} else {
++    echo "note: GetConsoleWindow returned 0x$($hwnd.ToString("X"))."
++    $sb = New-Object System.Text.StringBuilder -ArgumentList 4096
++    if ($WinAPI::GetWindowText($hwnd, $sb, $sb.Capacity)) {
++        $title = $sb.ToString()
++        echo "note: GetWindowText returned ""${title}""."
++        if ($title -eq "ConsoleWindowScript") {
++            echo "success!"
++        } else {
++            echo "error: expected to see ""ConsoleWindowScript""."
++            echo "  (Perhaps the console window is on a different window station?)"
++        }
++    } else {
++        echo "error: GetWindowText could not read the window title."
++        echo "  (Perhaps the console window is on a different window station?)"
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2b554c72c9fdc4a063e68a30251f0e9cdd51b183
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,87 @@@
++// Determines whether this is a new console by testing whether MARK moves the
++// cursor.
++//
++// WARNING: This test program may behave erratically if run under winpty.
++//
++
++#include <windows.h>
++
++#include <stdio.h>
++#include <string.h>
++
++#include "TestUtil.cc"
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
++
++static COORD getWindowPos(HANDLE conout) {
++    CONSOLE_SCREEN_BUFFER_INFO info = {};
++    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
++    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
++    return { info.srWindow.Left, info.srWindow.Top };
++}
++
++static COORD getWindowSize(HANDLE conout) {
++    CONSOLE_SCREEN_BUFFER_INFO info = {};
++    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
++    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
++    return {
++        static_cast<short>(info.srWindow.Right - info.srWindow.Left + 1),
++        static_cast<short>(info.srWindow.Bottom - info.srWindow.Top + 1)
++    };
++}
++
++static COORD getCursorPos(HANDLE conout) {
++    CONSOLE_SCREEN_BUFFER_INFO info = {};
++    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
++    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
++    return info.dwCursorPosition;
++}
++
++static void setCursorPos(HANDLE conout, COORD pos) {
++    BOOL ret = SetConsoleCursorPosition(conout, pos);
++    ASSERT(ret && "SetConsoleCursorPosition failed");
++}
++
++int main() {
++    const HANDLE conout = openConout();
++    const HWND hwnd = GetConsoleWindow();
++    ASSERT(hwnd != NULL && "GetConsoleWindow() returned NULL");
++
++    // With the legacy console, the Mark command moves the the cursor to the
++    // top-left cell of the visible console window.  Determine whether this
++    // is the new console by seeing if the cursor moves.
++
++    const auto windowSize = getWindowSize(conout);
++    if (windowSize.X <= 1) {
++        printf("Error: console window must be at least 2 columns wide\n");
++        trace("Error: console window must be at least 2 columns wide");
++        return 1;
++    }
++
++    bool cursorMoved = false;
++    const auto initialPos = getCursorPos(conout);
++
++    const auto windowPos = getWindowPos(conout);
++    setCursorPos(conout, { static_cast<short>(windowPos.X + 1), windowPos.Y });
++
++    {
++        const auto posA = getCursorPos(conout);
++        SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
++        const auto posB = getCursorPos(conout);
++        cursorMoved = memcmp(&posA, &posB, sizeof(posA)) != 0;
++        SendMessage(hwnd, WM_CHAR, 27, 0x00010001); // Send ESCAPE
++    }
++
++    setCursorPos(conout, initialPos);
++
++    if (cursorMoved) {
++        printf("Legacy console (i.e. MARK moved cursor)\n");
++        trace("Legacy console (i.e. MARK moved cursor)");
++    } else {
++        printf("Windows 10 new console (i.e MARK did not move cursor)\n");
++        trace("Windows 10 new console (i.e MARK did not move cursor)");
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..18460c6861e9e135483733f832f52fd0eac2c0ea
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,90 @@@
++Introduction
++============
++
++The only specification I could find describing mouse input escape sequences
++was the /usr/share/doc/xterm/ctlseqs.txt.gz file installed on my Ubuntu
++machine.
++
++Here are the relevant escape sequences:
++
++ * [ON] CSI '?' M 'h'                   Enable mouse input mode M
++ * [OFF] CSI '?' M 'l'                  Disable mouse input mode M
++ * [EVT] CSI 'M' F X Y                  Mouse event (default or mode 1005)
++ * [EVT6] CSI '<' F ';' X ';' Y 'M'     Mouse event with mode 1006
++ * [EVT6] CSI '<' F ';' X ';' Y 'm'     Mouse event with mode 1006 (up)
++ * [EVT15] CSI F ';' X ';' Y 'M'        Mouse event with mode 1015
++
++The first batch of modes affect what events are reported:
++
++ * 9: Presses only (not as well-supported as the other modes)
++ * 1000: Presses and releases
++ * 1002: Presses, releases, and moves-while-pressed
++ * 1003: Presses, releases, and all moves
++
++The next batch of modes affect the encoding of the mouse events:
++
++ * 1005: The X and Y coordinates are UTF-8 codepoints rather than bytes.
++ * 1006: Use the EVT6 sequences instead of EVT
++ * 1015: Use the EVT15 sequence instead of EVT (aka URVXT-mode)
++
++Support for modes in existing terminals
++=======================================
++
++                                 |  9   1000 1002 1003 | 1004 | overflow     | defhi | 1005 1006 1015
++---------------------------------+---------------------+------+--------------+-------+----------------
++Eclipse TM Terminal (Neon)       |  _    _    _    _   |  _   | n/a          | n/a   |  _    _    _
++gnome-terminal 3.6.2             |  X    X    X    X   |  _   | suppressed*b | 0x07  |  _    X    X
++iTerm2 2.1.4                     |  _    X    X    X   |  OI  | wrap*z       | n/a   |  X    X    X
++jediterm/IntelliJ                |  _    X    X    X   |  _   | ch='?'       | 0xff  |  X    X    X
++Konsole 2.13.2                   |  _    X    X    *a  |  _   | suppressed   | 0xff  |  X    X    X
++mintty 2.2.2                     |  X    X    X    X   |  OI  | ch='\0'      | 0xff  |  X    X    X
++putty 0.66                       |  _    X    X    _   |  _   | suppressed   | 0xff  |  _    X    X
++rxvt 2.7.10                      |  X    X    _    _   |  _   | wrap*z       | n/a   |  _    _    _
++screen(under xterm)              |  X    X    X    X   |  _   | suppressed   | 0xff  |  _    _    _
++urxvt 9.21                       |  X    X    X    X   |  _   | wrap*z       | n/a   |  X    _    X
++xfce4-terminal 0.6.3 (GTK2 VTE)  |  X    X    X    X   |  _   | wrap         | n/a   |  _    _    _
++xterm                            |  X    X    X    X   |  OI  | ch='\0'      | 0xff  |  X    X    X
++
++*a: Mode 1003 is handled the same way as 1002.
++*b: The coordinate wraps from 0xff to 0x00, then maxs out at 0x07.  I'm
++    guessing this behavior is a bug?  I'm using the Xubuntu 14.04
++    gnome-terminal.
++*z: These terminals have a bug where column 224 (and row 224, presumably)
++    yields a truncated escape sequence.  224 + 32 is 0, so it would normally
++    yield `CSI 'M' F '\0' Y`, but the '\0' is interpreted as a NUL-terminator.
++
++Problem 1: How do these flags work?
++===================================
++
++Terminals accept the OFF sequence with any of the input modes.  This makes
++little sense--there are two multi-value settings, not seven independent flags!
++
++All the terminals handle Granularity the same way.  ON-Granularity sets
++Granularity to the specified value, and OFF-Granularity sets Granularity to
++OFF.
++
++Terminals vary in how they handle the Encoding modes.  For example:
++
++ * xterm.  ON-Encoding sets Encoding.  OFF-Encoding with a non-active Encoding
++   has no effect.  OFF-Encoding otherwise resets Encoding to Default.
++
++ * mintty (tested 2.2.2), iTerm2 2.1.4, and jediterm.  ON-Encoding sets
++   Encoding.  OFF-Encoding resets Encoding to Default.
++
++ * Konsole (tested 2.13.2) seems to configure each encoding method
++   independently.  The effective Encoding is the first enabled encoding in this
++   list:
++    - Mode 1006
++    - Mode 1015
++    - Mode 1005
++    - Default
++
++ * gnome-terminal (tested 3.6.2) also configures each encoding method
++   independently.  The effective Encoding is the first enabled encoding in
++   this list:
++    - Mode 1006
++    - Mode 1015
++    - Default
++   Mode 1005 is not supported.
++
++ * xfce4 terminal 0.6.3 (GTK2 VTE) always outputs the default encoding method.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7d9684fe94ebc90bd8adc086fb6a93f458842270
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,34 @@@
++#include <windows.h>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    if (argc != 3 && argc != 5) {
++        printf("Usage: %s x y\n", argv[0]);
++        printf("Usage: %s x y width height\n", argv[0]);
++        return 1;
++    }
++
++    HWND hwnd = GetConsoleWindow();
++
++    const int x = atoi(argv[1]);
++    const int y = atoi(argv[2]);
++
++    int w = 0, h = 0;
++    if (argc == 3) {
++        RECT r = {};
++        BOOL ret = GetWindowRect(hwnd, &r);
++        ASSERT(ret && "GetWindowRect failed on console window");
++        w = r.right - r.left;
++        h = r.bottom - r.top;
++    } else {
++        w = atoi(argv[3]);
++        h = atoi(argv[4]);
++    }
++
++    BOOL ret = MoveWindow(hwnd, x, y, w, h, TRUE);
++    trace("MoveWindow: ret=%d", ret);
++    printf("MoveWindow: ret=%d\n", ret);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..410e1841986e91dc80f27350a81343681bca810b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,219 @@@
++Test programs
++-------------
++
++Cygwin
++  emacs
++  vim
++  mc     (Midnight Commander)
++  lynx
++  links
++  less
++  more
++  wget
++
++Capturing the console output
++----------------------------
++
++Initial idea:
++
++In the agent, keep track of the remote terminal state for N lines of
++(window+history).  Also keep track of the terminal size.  Regularly poll for
++changes to the console screen buffer, then use some number of edits to bring
++the remote terminal into sync with the console.
++
++This idea seems to have trouble when a Unix terminal is resized.  When the
++server receives a resize notification, it can have a hard time figuring out
++what the terminal did.  Race conditions might also be a problem.
++
++The behavior of the terminal can be tricky:
++
++ - When the window is expanded by one line, does the terminal add a blank line
++   to the bottom or move a line from the history into the top?
++
++ - When the window is shrunk by one line, does the terminal delete the topmost
++   or the bottommost line?  Can it delete the line with the cursor?
++
++Some popular behaviors for expanding:
++ - [all] If there are no history lines, then add a line at the bottom.
++ - [konsole] Always add a line at the bottom.
++ - [putty,xterm,rxvt] Pull in a history line from the top.
++ - [g-t] I can't tell.  It seems to add a blank line, until the program writes
++   to stdout or until I click the scroll bar, then the output "snaps" back down,
++   pulling lines out of the history.  I thought I saw different behavior
++   between Ubuntu 10.10 and 11.10, so maybe GNOME 3 changed something.  Avoid
++   using "bash" to test this behavior because "bash" apparently always writes
++   the prompt after terminal resize.
++
++Some popular behaviors for shrinking:
++ - [konsole,putty,xterm,rxvt] If the line at the bottom is blank, then delete
++   it.  Otherwise, move the topmost line into history.
++ - [g-t] If the line at the bottom has not been touched, then delete it.
++   Otherwise, move the topmost line into history.
++
++(TODO: I need to test my theories about the terminal behavior better still.
++It's interesting to see how g-t handles clear differently than every other
++terminal.)
++
++There is an ANSI escape sequence (DSR) that sends the current cursor location
++to the terminal's input.  One idea I had was to use this code to figure out how
++the terminal had handled a resize.  I currently think this idea won't work due
++to race conditions.
++
++Newer idea:
++
++Keep track of the last N lines that have been sent to the remote terminal.
++Poll for changes to console output.  When the output changes, send just the
++changed content to the terminal.  In particular:
++ - Don't send a cursor position (CUP) code.  Instead, if the line that's 3
++   steps up from the latest line changes, send a relative cursor up (CUU)
++   code.  It's OK to send an absolute column number code (CHA).
++ - At least in general, don't try to send complete screenshots of the current
++   console window.
++
++The idea is that sending just the changes should have good behavior for streams
++of output, even when those streams modify the output (e.g. an archiver, or
++maybe a downloader/packager/wget).  I need to think about whether this works
++for full-screen programs (e.g. emacs, less, lynx, the above list of programs).
++
++I noticed that console programs don't typically modify the window or buffer
++coordinates.  edit.com is an exception.
++
++I tested the pager in native Python (more?), and I verified that ENTER and SPACE
++both paid no attention to the location of the console window within the screen
++buffer.  This makes sense -- why would they care?  The Cygwin less, on the other
++hand, does care.  If I scroll the window up, then Cygwin less will write to a
++position within the window.  I didn't really expect this behavior, but it
++doesn't seem to be a problem.
++
++Setting up a TestNetServer service
++----------------------------------
++
++First run the deploy.sh script to copy files into deploy.  Make sure
++TestNetServer.exe will run in a bare environment (no MinGW or Qt in the path).
++
++Install the Windows Server 2003 Resource Kit.  It will have two programs in it,
++instsrv and srvany.
++
++Run:
++
++  InstSrv TestNetServer <path-to-srvany>\srvany.exe
++
++This creates a service named "TestNetServer" that uses the Microsoft service
++wrapper.  To configure the new service to run TestNetServer, set a registry
++value:
++
++  [HKLM\SYSTEM\CurrentControlSet\Services\TestNetServer\Parameters]
++  Application=<full-path>\TestNetServer.exe
++
++Also see http://www.iopus.com/guides/srvany.htm.
++
++To remove the service, run:
++
++  InstSrv TestNetServer REMOVE
++
++TODO
++----
++
++Agent: When resizing the console, consider whether to add lines to the top
++or bottom.  I remember thinking the current behavior was wrong for some
++application, but I forgot which one.
++
++Make the font as small as possible.  The console window dimensions are limited by
++the screen size, so making the font small reduces an unnecessary limitation on the
++PseudoConsole size.  There's a documented Vista/Win7 API for this
++(SetCurrentConsoleFontEx), and apparently WinXP has an undocumented API
++(SetConsoleFont):
++    http://blogs.microsoft.co.il/blogs/pavely/archive/2009/07/23/changing-console-fonts.aspx
++
++Make the agent work with DOS programs like edit and qbasic.
++ - Detect that the terminal program has resized the window/buffer and enter a
++   simple just-scrape-and-dont-resize mode.  Track the client window size and
++   send the intersection of the console and the agent's client.
++ - I also need to generate keyboard scan codes.
++ - Solve the NTVDM.EXE console shutdown problem, probably by ignoring NTVDM.EXE
++   when it appears on the GetConsoleProcessList list.
++
++Rename the agent?  Is the term "proxy" more accurate?
++
++Optimize the polling.  e.g. Use a longer poll interval when the console is idle.
++Do a minimal poll that checks whether the sync marker or window has moved.
++
++Increase the console buffer size to ~9000 lines.  Beware making it so big that
++reading the sync column exhausts the 32KB conhost<->agent heap.
++
++Reduce the memory overhead of the agent.  The agent's m_bufferData array can
++be small (a few hundred lines?) relative to the console buffer size.
++
++Try to handle console background color better.
++    Unix terminal emulators have a user-configurable foreground and background
++color, and for best results, the agent really needs to avoid changing the colors,
++especially the background color.  It's undesirable/ugly to SSH into a machine
++and see the command prompt change the colors.  It's especially ugly that the
++terminal retains its original colors and only drawn cells get the new colors.
++(e.g. Resizing the window to the right uses the local terminal colors rather
++than the remote colors.)  It's especially ugly in gnome-terminal, which draws
++user-configurable black as black, but VT100 black as dark-gray.
++    If there were a way to query the terminal emulator's colors, then I could
++match the console's colors to the terminal and everything would just work.  As
++far as I know, that's not possible.
++    I thought of a kludge that might work.  Instead of translating console white
++and black to VT/100 white and black, I would translate them to "reset" and
++"invert".  I'd translate other colors normally.  This approach should produce
++ideal results for command-line work and tolerable results for full-screen
++programs without configuration.  Configuring the agent for black-on-white or
++white-on-black would produce ideal results in all situations.
++    This kludge only really applies to the SSH application.  For a Win32 Konsole
++application, it should be easy to get the colors right all the time.
++
++Try using the screen reader API:
++ - To eliminate polling.
++ - To detect when a line wraps.  When a line wraps, it'd be nice not to send a
++   CRLF to the terminal emulator so copy-and-paste works better.
++ - To detect hard tabs with Cygwin.
++
++Implement VT100/ANSI escape sequence recognition for input.  Decide where this
++functionality belongs.  PseudoConsole.dll?  Disambiguating ESC from an escape
++sequence might be tricky.  For the SSH server, I was thinking that when a small
++SSH payload ended with an ESC character, I could assume the character was really
++an ESC keypress, on the assumption that if it were an escape sequence, the
++payload would probably contain the whole sequence.  I'm not sure this works,
++especially if there's a lot of other traffic multiplexed on the SSH socket.
++
++Support Unicode.
++ - Some DOS programs draw using line/box characters.  Can these characters be
++   translated to the Unicode equivalents?
++
++Create automated tests.
++
++Experiment with the Terminator emulator, an emulator that doesn't wrap lines.
++How many columns does it report having?  What column does it report the cursor
++in as it's writing past the right end of the window?  Will Terminator be a
++problem if I implement line wrapping detection in the agent?
++
++BUG: After the unix-adapter/pconsole.exe program exits, the blinking cursor is
++replaced with a hidden cursor.
++
++Fix assert() in the agent.  If it fails, the failure message needs to be
++reported somewhere.  Pop up a dialog box?  Maybe switch the active desktop,
++then show a dialog box?
++
++TODO: There's already a pconsole project on GitHub.  Maybe rename this project
++to something else?  winpty?
++
++TODO: Can the DebugServer system be replaced with OutputDebugString?  How
++do we decide whose processes' output to collect?
++
++TODO: Three executables:
++  build/winpty-agent.exe
++  build/winpty.dll
++  build/console.exe
++
++BUG: Run the pconsole.exe inside another console.  As I type dir, I see this:
++      D:\rprichard\pconsole>
++      D:\rprichard\pconsole>d
++      D:\rprichard\pconsole>di
++      D:\rprichard\pconsole>dir
++    In the output of "dir", every other line is blank.
++    There was a bug in Terminal::sendLine that was causing this to happen
++    frequently.  Now that I fixed it, this bug should only manifest on lines
++    whose last column is not a space (i.e. a full line).
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..456708f05b170b9ebdd293ce994578b4797cd1f0
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,27 @@@
++#include <windows.h>
++
++#include <assert.h>
++#include <locale.h>
++#include <stdio.h>
++
++#include <iostream>
++
++int main() {
++    setlocale(LC_ALL, "");
++
++    OSVERSIONINFOEXW info = {0};
++    info.dwOSVersionInfoSize = sizeof(info);
++    assert(GetVersionExW((OSVERSIONINFOW*)&info));
++
++    printf("dwMajorVersion      = %d\n", (int)info.dwMajorVersion);
++    printf("dwMinorVersion      = %d\n", (int)info.dwMinorVersion);
++    printf("dwBuildNumber       = %d\n", (int)info.dwBuildNumber);
++    printf("dwPlatformId        = %d\n", (int)info.dwPlatformId);
++    printf("szCSDVersion        = %ls\n", info.szCSDVersion);
++    printf("wServicePackMajor   = %d\n", info.wServicePackMajor);
++    printf("wServicePackMinor   = %d\n", info.wServicePackMinor);
++    printf("wSuiteMask          = 0x%x\n", (unsigned int)info.wSuiteMask);
++    printf("wProductType        = 0x%x\n", (unsigned int)info.wProductType);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..656d4f126df222a13351d44d313c91a89b740c62
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,101 @@@
++//
++// Verify that console selection blocks writes to an inactive console screen
++// buffer.  Writes TEST PASSED or TEST FAILED to the popup console window.
++//
++
++#include <windows.h>
++#include <stdio.h>
++
++#include <string>
++
++#include "TestUtil.cc"
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
++
++bool g_useMark = false;
++
++CALLBACK DWORD pausingThread(LPVOID dummy)
++{
++    HWND hwnd = GetConsoleWindow();
++    trace("Sending selection to freeze");
++    SendMessage(hwnd, WM_SYSCOMMAND,
++        g_useMark ? SC_CONSOLE_MARK :
++                    SC_CONSOLE_SELECT_ALL,
++        0);
++    Sleep(1000);
++    trace("Sending escape WM_CHAR to unfreeze");
++    SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
++    Sleep(1000);
++}
++
++static HANDLE createBuffer() {
++    HANDLE buf = CreateConsoleScreenBuffer(
++        GENERIC_READ | GENERIC_WRITE,
++        FILE_SHARE_READ | FILE_SHARE_WRITE,
++        NULL,
++        CONSOLE_TEXTMODE_BUFFER,
++        NULL);
++    ASSERT(buf != INVALID_HANDLE_VALUE);
++    return buf;
++}
++
++static void runTest(bool useMark, bool createEarly) {
++    trace("=======================================");
++    trace("useMark=%d createEarly=%d", useMark, createEarly);
++    g_useMark = useMark;
++    HANDLE buf = INVALID_HANDLE_VALUE;
++
++    if (createEarly) {
++        buf = createBuffer();
++    }
++
++    CreateThread(NULL, 0,
++         pausingThread, NULL,
++         0, NULL);
++    Sleep(500);
++
++    if (!createEarly) {
++        trace("Creating buffer");
++        TimeMeasurement tm1;
++        buf = createBuffer();
++        const double elapsed1 = tm1.elapsed();
++        if (elapsed1 >= 0.250) {
++            printf("!!! TEST FAILED !!!\n");
++            Sleep(2000);
++            return;
++        }
++    }
++
++    trace("Writing to aux buffer");
++    TimeMeasurement tm2;
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleW(buf, L"HI", 2, &actual, NULL);
++    const double elapsed2 = tm2.elapsed();
++    trace("Writing to aux buffer: finished: ret=%d actual=%d (elapsed=%1.3f)", ret, actual, elapsed2);
++    if (elapsed2 < 0.250) {
++        printf("!!! TEST FAILED !!!\n");
++    } else {
++        printf("TEST PASSED\n");
++    }
++    Sleep(2000);
++}
++
++int main(int argc, char **argv) {
++    if (argc == 1) {
++        startChildProcess(L"child");
++        return 0;
++    }
++
++    std::string arg = argv[1];
++    if (arg == "child") {
++        for (int useMark = 0; useMark <= 1; useMark++) {
++            for (int createEarly = 0; createEarly <= 1; createEarly++) {
++                runTest(useMark, createEarly);
++            }
++        }
++        printf("done...\n");
++        Sleep(1000);
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..fa584b9fae901a2038cf966af3812a82cf529de9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,671 @@@
++//
++// Windows versions tested
++//
++// Vista Enterprise SP2 32-bit
++//  - ver reports [Version 6.0.6002]
++//  - kernel32.dll product/file versions are 6.0.6002.19381
++//
++// Windows 7 Ultimate SP1 32-bit
++//  - ver reports [Version 6.1.7601]
++//  - conhost.exe product/file versions are 6.1.7601.18847
++//  - kernel32.dll product/file versions are 6.1.7601.18847
++//
++// Windows Server 2008 R2 Datacenter SP1 64-bit
++//  - ver reports [Version 6.1.7601]
++//  - conhost.exe product/file versions are 6.1.7601.23153
++//  - kernel32.dll product/file versions are 6.1.7601.23153
++//
++// Windows 8 Enterprise 32-bit
++//  - ver reports [Version 6.2.9200]
++//  - conhost.exe product/file versions are 6.2.9200.16578
++//  - kernel32.dll product/file versions are 6.2.9200.16859
++//
++
++//
++// Specific version details on working Server 2008 R2:
++//
++//      dwMajorVersion      = 6
++//      dwMinorVersion      = 1
++//      dwBuildNumber       = 7601
++//      dwPlatformId        = 2
++//      szCSDVersion        = Service Pack 1
++//      wServicePackMajor   = 1
++//      wServicePackMinor   = 0
++//      wSuiteMask          = 0x190
++//      wProductType        = 0x3
++//
++// Specific version details on broken Win7:
++//
++//      dwMajorVersion      = 6
++//      dwMinorVersion      = 1
++//      dwBuildNumber       = 7601
++//      dwPlatformId        = 2
++//      szCSDVersion        = Service Pack 1
++//      wServicePackMajor   = 1
++//      wServicePackMinor   = 0
++//      wSuiteMask          = 0x100
++//      wProductType        = 0x1
++//
++
++#include <windows.h>
++#include <stdio.h>
++#include <string.h>
++
++#include "TestUtil.cc"
++
++const char *g_prefix = "";
++
++static void dumpHandles() {
++    trace("%sSTDIN=0x%I64x STDOUT=0x%I64x STDERR=0x%I64x",
++        g_prefix,
++        (long long)GetStdHandle(STD_INPUT_HANDLE),
++        (long long)GetStdHandle(STD_OUTPUT_HANDLE),
++        (long long)GetStdHandle(STD_ERROR_HANDLE));
++}
++
++static const char *successOrFail(BOOL ret) {
++    return ret ? "ok" : "FAILED";
++}
++
++static void startChildInSameConsole(const wchar_t *args, BOOL
++                                    bInheritHandles=FALSE) {
++    wchar_t program[1024];
++    wchar_t cmdline[1024];
++    GetModuleFileNameW(NULL, program, 1024);
++    swprintf(cmdline, L"\"%ls\" %ls", program, args);
++
++    STARTUPINFOW sui;
++    PROCESS_INFORMATION pi;
++    memset(&sui, 0, sizeof(sui));
++    memset(&pi, 0, sizeof(pi));
++    sui.cb = sizeof(sui);
++
++    CreateProcessW(program, cmdline,
++                   NULL, NULL,
++                   /*bInheritHandles=*/bInheritHandles,
++                   /*dwCreationFlags=*/0,
++                   NULL, NULL,
++                   &sui, &pi);
++}
++
++static void closeHandle(HANDLE h) {
++    trace("%sClosing handle 0x%I64x...", g_prefix, (long long)h);
++    trace("%sClosing handle 0x%I64x... %s", g_prefix, (long long)h, successOrFail(CloseHandle(h)));
++}
++
++static HANDLE createBuffer() {
++
++    // If sa isn't provided, the handle defaults to not-inheritable.
++    SECURITY_ATTRIBUTES sa = {0};
++    sa.nLength = sizeof(sa);
++    sa.bInheritHandle = TRUE;
++
++    trace("%sCreating a new buffer...", g_prefix);
++    HANDLE conout = CreateConsoleScreenBuffer(
++                GENERIC_READ | GENERIC_WRITE,
++                FILE_SHARE_READ | FILE_SHARE_WRITE,
++                &sa,
++                CONSOLE_TEXTMODE_BUFFER, NULL);
++
++    trace("%sCreating a new buffer... 0x%I64x", g_prefix, (long long)conout);
++    return conout;
++}
++
++static HANDLE openConout() {
++
++    // If sa isn't provided, the handle defaults to not-inheritable.
++    SECURITY_ATTRIBUTES sa = {0};
++    sa.nLength = sizeof(sa);
++    sa.bInheritHandle = TRUE;
++
++    trace("%sOpening CONOUT...", g_prefix);
++    HANDLE conout = CreateFileW(L"CONOUT$",
++                GENERIC_READ | GENERIC_WRITE,
++                FILE_SHARE_READ | FILE_SHARE_WRITE,
++                &sa,
++                OPEN_EXISTING, 0, NULL);
++    trace("%sOpening CONOUT... 0x%I64x", g_prefix, (long long)conout);
++    return conout;
++}
++
++static void setConsoleActiveScreenBuffer(HANDLE conout) {
++    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called...",
++        g_prefix, (long long)conout);
++    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called... %s",
++        g_prefix, (long long)conout,
++        successOrFail(SetConsoleActiveScreenBuffer(conout)));
++}
++
++static void writeTest(HANDLE conout, const char *msg) {
++    char writeData[256];
++    sprintf(writeData, "%s%s\n", g_prefix, msg);
++
++    trace("%sWriting to 0x%I64x: '%s'...",
++        g_prefix, (long long)conout, msg);
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleA(conout, writeData, strlen(writeData), &actual, NULL);
++    trace("%sWriting to 0x%I64x: '%s'... %s",
++        g_prefix, (long long)conout, msg,
++        successOrFail(ret && actual == strlen(writeData)));
++}
++
++static void writeTest(const char *msg) {
++    writeTest(GetStdHandle(STD_OUTPUT_HANDLE), msg);
++}
++
++
++
++///////////////////////////////////////////////////////////////////////////////
++// TEST 1 -- create new buffer, activate it, and close the handle.  The console
++// automatically switches the screen buffer back to the original.
++//
++// This test passes everywhere.
++//
++
++static void test1(int argc, char *argv[]) {
++    if (!strcmp(argv[1], "1")) {
++        startChildProcess(L"1:child");
++        return;
++    }
++
++    HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
++    writeTest(origBuffer, "<-- origBuffer -->");
++
++    HANDLE newBuffer = createBuffer();
++    writeTest(newBuffer, "<-- newBuffer -->");
++    setConsoleActiveScreenBuffer(newBuffer);
++    Sleep(2000);
++
++    writeTest(origBuffer, "TEST PASSED!");
++
++    // Closing the handle w/o switching the active screen buffer automatically
++    // switches the console back to the original buffer.
++    closeHandle(newBuffer);
++
++    while (true) {
++        Sleep(1000);
++    }
++}
++
++
++
++///////////////////////////////////////////////////////////////////////////////
++// TEST 2 -- Test program that creates and activates newBuffer, starts a child
++// process, then closes its newBuffer handle.  newBuffer remains activated,
++// because the child keeps it active.  (Also see TEST D.)
++//
++
++static void test2(int argc, char *argv[]) {
++    if (!strcmp(argv[1], "2")) {
++        startChildProcess(L"2:parent");
++        return;
++    }
++
++    if (!strcmp(argv[1], "2:parent")) {
++        g_prefix = "parent: ";
++        dumpHandles();
++        HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
++        writeTest(origBuffer, "<-- origBuffer -->");
++
++        HANDLE newBuffer = createBuffer();
++        writeTest(newBuffer, "<-- newBuffer -->");
++        setConsoleActiveScreenBuffer(newBuffer);
++
++        Sleep(1000);
++        writeTest(newBuffer, "bInheritHandles=FALSE:");
++        startChildInSameConsole(L"2:child", FALSE);
++        Sleep(1000);
++        writeTest(newBuffer, "bInheritHandles=TRUE:");
++        startChildInSameConsole(L"2:child", TRUE);
++
++        Sleep(1000);
++        trace("parent:----");
++
++        // Close the new buffer.  The active screen buffer doesn't automatically
++        // switch back to origBuffer, because the child process has a handle open
++        // to the original buffer.
++        closeHandle(newBuffer);
++
++        Sleep(600 * 1000);
++        return;
++    }
++
++    if (!strcmp(argv[1], "2:child")) {
++        g_prefix = "child: ";
++        dumpHandles();
++        // The child's output isn't visible, because it's still writing to
++        // origBuffer.
++        trace("child:----");
++        writeTest("writing to STDOUT");
++
++        // Handle inheritability is curious.  The console handles this program
++        // creates are inheritable, but CreateProcess is called with both
++        // bInheritHandles=TRUE and bInheritHandles=FALSE.
++        //
++        // Vista and Windows 7: bInheritHandles has no effect.  The child and
++        // parent processes have the same STDIN/STDOUT/STDERR handles:
++        // 0x3, 0x7, and 0xB.  The parent has a 0xF handle for newBuffer.
++        // The child can only write to 0x7, 0xB, and 0xF.  Only the writes to
++        // 0xF are visible (i.e. they touch newBuffer).
++        //
++        // Windows 8 or Windows 10 (legacy or non-legacy): the lowest 2 bits of
++        // the HANDLE to WriteConsole seem to be ignored.  The new process'
++        // console handles always refer to the buffer that was active when they
++        // started, but the values of the handles depend upon bInheritHandles.
++        // With bInheritHandles=TRUE, the child has the same
++        // STDIN/STDOUT/STDERR/newBuffer handles as the parent, and the three
++        // output handles all work, though their output is all visible.  With
++        // bInheritHandles=FALSE, the child has different STDIN/STDOUT/STDERR
++        // handles, and only the new STDOUT/STDERR handles work.
++        //
++        for (unsigned int i = 0x1; i <= 0xB0; ++i) {
++            char msg[256];
++            sprintf(msg, "Write to handle 0x%x", i);
++            HANDLE h = reinterpret_cast<HANDLE>(i);
++            writeTest(h, msg);
++        }
++
++        Sleep(600 * 1000);
++        return;
++    }
++}
++
++
++
++///////////////////////////////////////////////////////////////////////////////
++// TEST A -- demonstrate an apparent Windows bug with screen buffers
++//
++// Steps:
++//  - The parent starts a child process.
++//  - The child process creates and activates newBuffer
++//  - The parent opens CONOUT$ and writes to it.
++//  - The parent closes CONOUT$.
++//     - At this point, broken Windows reactivates origBuffer.
++//  - The child writes to newBuffer again.
++//  - The child activates origBuffer again, then closes newBuffer.
++//
++// Test passes if the message "TEST PASSED!" is visible.
++// Test commonly fails if conhost.exe crashes.
++//
++// Results:
++//  - Windows 7 Ultimate SP1 32-bit: conhost.exe crashes
++//  - Windows Server 2008 R2 Datacenter SP1 64-bit: PASS
++//  - Windows 8 Enterprise 32-bit: PASS
++//  - Windows 10 64-bit (legacy and non-legacy): PASS
++//
++
++static void testA_parentWork() {
++    // Open an extra CONOUT$ handle so that the HANDLE values in parent and
++    // child don't collide.  I think it's OK if they collide, but since we're
++    // trying to track down a Windows bug, it's best to avoid unnecessary
++    // complication.
++    HANDLE dummy = openConout();
++
++    Sleep(3000);
++
++    // Step 2: Open CONOUT$ in the parent.  This opens the active buffer, which
++    // was just created in the child.  It's handle 0x13.  Write to it.
++
++    HANDLE newBuffer = openConout();
++    writeTest(newBuffer, "step2: writing to newBuffer");
++
++    Sleep(3000);
++
++    // Step 3: Close handle 0x13.  With Windows 7, the console switches back to
++    // origBuffer, and (unless I'm missing something) it shouldn't.
++
++    closeHandle(newBuffer);
++}
++
++static void testA_childWork() {
++    HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    //
++    // Step 1: Create the new screen buffer in the child process and make it
++    // active.  (Typically, it's handle 0x0F.)
++    //
++
++    HANDLE newBuffer = createBuffer();
++
++    setConsoleActiveScreenBuffer(newBuffer);
++    writeTest(newBuffer, "<-- newBuffer -->");
++
++    Sleep(9000);
++    trace("child:----");
++
++    // Step 4: write to the newBuffer again.
++    writeTest(newBuffer, "TEST PASSED!");
++
++    //
++    // Step 5: Switch back to the original screen buffer and close the new
++    // buffer.  The switch call succeeds, but the CloseHandle call freezes for
++    // several seconds, because conhost.exe crashes.
++    //
++    Sleep(3000);
++
++    setConsoleActiveScreenBuffer(origBuffer);
++    writeTest(origBuffer, "writing to origBuffer");
++
++    closeHandle(newBuffer);
++
++    // The console HWND is NULL.
++    trace("child: console HWND=0x%I64x", (long long)GetConsoleWindow());
++
++    // At this point, the console window has closed, but the parent/child
++    // processes are still running.  Calling AllocConsole would fail, but
++    // calling FreeConsole followed by AllocConsole would both succeed, and a
++    // new console would appear.
++}
++
++static void testA(int argc, char *argv[]) {
++
++    if (!strcmp(argv[1], "A")) {
++        startChildProcess(L"A:parent");
++        return;
++    }
++
++    if (!strcmp(argv[1], "A:parent")) {
++        g_prefix = "parent: ";
++        trace("parent:----");
++        dumpHandles();
++        writeTest("<-- origBuffer -->");
++        startChildInSameConsole(L"A:child");
++        testA_parentWork();
++        Sleep(120000);
++        return;
++    }
++
++    if (!strcmp(argv[1], "A:child")) {
++        g_prefix = "child: ";
++        dumpHandles();
++        testA_childWork();
++        Sleep(120000);
++        return;
++    }
++}
++
++
++
++///////////////////////////////////////////////////////////////////////////////
++// TEST B -- invert TEST A -- also crashes conhost on Windows 7
++//
++// Test passes if the message "TEST PASSED!" is visible.
++// Test commonly fails if conhost.exe crashes.
++//
++// Results:
++//  - Windows 7 Ultimate SP1 32-bit: conhost.exe crashes
++//  - Windows Server 2008 R2 Datacenter SP1 64-bit: PASS
++//  - Windows 8 Enterprise 32-bit: PASS
++//  - Windows 10 64-bit (legacy and non-legacy): PASS
++//
++
++static void testB(int argc, char *argv[]) {
++    if (!strcmp(argv[1], "B")) {
++        startChildProcess(L"B:parent");
++        return;
++    }
++
++    if (!strcmp(argv[1], "B:parent")) {
++        g_prefix = "parent: ";
++        startChildInSameConsole(L"B:child");
++        writeTest("<-- origBuffer -->");
++        HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
++
++        //
++        // Step 1: Create the new buffer and make it active.
++        //
++        trace("%s----", g_prefix);
++        HANDLE newBuffer = createBuffer();
++        setConsoleActiveScreenBuffer(newBuffer);
++        writeTest(newBuffer, "<-- newBuffer -->");
++
++        //
++        // Step 4: Attempt to write again to the new buffer.
++        //
++        Sleep(9000);
++        trace("%s----", g_prefix);
++        writeTest(newBuffer, "TEST PASSED!");
++
++        //
++        // Step 5: Switch back to the original buffer.
++        //
++        Sleep(3000);
++        trace("%s----", g_prefix);
++        setConsoleActiveScreenBuffer(origBuffer);
++        closeHandle(newBuffer);
++        writeTest(origBuffer, "writing to the initial buffer");
++
++        Sleep(60000);
++        return;
++    }
++
++    if (!strcmp(argv[1], "B:child")) {
++        g_prefix = "child: ";
++        Sleep(3000);
++        trace("%s----", g_prefix);
++
++        //
++        // Step 2: Open the newly active buffer and write to it.
++        //
++        HANDLE newBuffer = openConout();
++        writeTest(newBuffer, "writing to newBuffer");
++
++        //
++        // Step 3: Close the newly active buffer.
++        //
++        Sleep(3000);
++        closeHandle(newBuffer);
++
++        Sleep(60000);
++        return;
++    }
++}
++
++
++
++///////////////////////////////////////////////////////////////////////////////
++// TEST C -- Interleaving open/close of console handles also seems to break on
++// Windows 7.
++//
++// Test:
++//  - child creates and activates newBuf1
++//  - parent opens newBuf1
++//  - child creates and activates newBuf2
++//  - parent opens newBuf2, then closes newBuf1
++//  - child switches back to newBuf1
++//     * At this point, the console starts malfunctioning.
++//  - parent and child close newBuf2
++//  - child closes newBuf1
++//
++// Test passes if the message "TEST PASSED!" is visible.
++// Test commonly fails if conhost.exe crashes.
++//
++// Results:
++//  - Windows 7 Ultimate SP1 32-bit: conhost.exe crashes
++//  - Windows Server 2008 R2 Datacenter SP1 64-bit: PASS
++//  - Windows 8 Enterprise 32-bit: PASS
++//  - Windows 10 64-bit (legacy and non-legacy): PASS
++//
++
++static void testC(int argc, char *argv[]) {
++    if (!strcmp(argv[1], "C")) {
++        startChildProcess(L"C:parent");
++        return;
++    }
++
++    if (!strcmp(argv[1], "C:parent")) {
++        startChildInSameConsole(L"C:child");
++        writeTest("<-- origBuffer -->");
++        g_prefix = "parent: ";
++
++        // At time=4, open newBuffer1.
++        Sleep(4000);
++        trace("%s---- t=4", g_prefix);
++        const HANDLE newBuffer1 = openConout();
++
++        // At time=8, open newBuffer2, and close newBuffer1.
++        Sleep(4000);
++        trace("%s---- t=8", g_prefix);
++        const HANDLE newBuffer2 = openConout();
++        closeHandle(newBuffer1);
++
++        // At time=25, cleanup of newBuffer2.
++        Sleep(17000);
++        trace("%s---- t=25", g_prefix);
++        closeHandle(newBuffer2);
++
++        Sleep(240000);
++        return;
++    }
++
++    if (!strcmp(argv[1], "C:child")) {
++        g_prefix = "child: ";
++
++        // At time=2, create newBuffer1 and activate it.
++        Sleep(2000);
++        trace("%s---- t=2", g_prefix);
++        const HANDLE newBuffer1 = createBuffer();
++        setConsoleActiveScreenBuffer(newBuffer1);
++        writeTest(newBuffer1, "<-- newBuffer1 -->");
++
++        // At time=6, create newBuffer2 and activate it.
++        Sleep(4000);
++        trace("%s---- t=6", g_prefix);
++        const HANDLE newBuffer2 = createBuffer();
++        setConsoleActiveScreenBuffer(newBuffer2);
++        writeTest(newBuffer2, "<-- newBuffer2 -->");
++
++        // At time=10, attempt to switch back to newBuffer1.  The parent process
++        // has opened and closed its handle to newBuffer1, so does it still exist?
++        Sleep(4000);
++        trace("%s---- t=10", g_prefix);
++        setConsoleActiveScreenBuffer(newBuffer1);
++        writeTest(newBuffer1, "write to newBuffer1: TEST PASSED!");
++
++        // At time=25, cleanup of newBuffer2.
++        Sleep(15000);
++        trace("%s---- t=25", g_prefix);
++        closeHandle(newBuffer2);
++
++        // At time=35, cleanup of newBuffer1.  The console should switch to the
++        // initial buffer again.
++        Sleep(10000);
++        trace("%s---- t=35", g_prefix);
++        closeHandle(newBuffer1);
++
++        Sleep(240000);
++        return;
++    }
++}
++
++
++
++///////////////////////////////////////////////////////////////////////////////
++// TEST D -- parent creates a new buffer, child launches, writes,
++// closes it output handle, then parent writes again.  (Also see TEST 2.)
++//
++// On success, this will appear:
++//
++//    parent: <-- newBuffer -->
++//    child: writing to newBuffer
++//    parent: TEST PASSED!
++//
++// If this appears, it indicates that the child's closing its output handle did
++// not destroy newBuffer.
++//
++// Results:
++//  - Windows 7 Ultimate SP1 32-bit: PASS
++//  - Windows 8 Enterprise 32-bit: PASS
++//  - Windows 10 64-bit (legacy and non-legacy): PASS
++//
++
++static void testD(int argc, char *argv[]) {
++    if (!strcmp(argv[1], "D")) {
++        startChildProcess(L"D:parent");
++        return;
++    }
++
++    if (!strcmp(argv[1], "D:parent")) {
++        g_prefix = "parent: ";
++        HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
++        writeTest(origBuffer, "<-- origBuffer -->");
++
++        HANDLE newBuffer = createBuffer();
++        writeTest(newBuffer, "<-- newBuffer -->");
++        setConsoleActiveScreenBuffer(newBuffer);
++
++        // At t=2, start a child process, explicitly forcing it to use
++        // newBuffer for its standard handles.  These calls are apparently
++        // redundant on Windows 8 and up.
++        Sleep(2000);
++        trace("parent:----");
++        trace("parent: starting child process");
++        SetStdHandle(STD_OUTPUT_HANDLE, newBuffer);
++        SetStdHandle(STD_ERROR_HANDLE, newBuffer);
++        startChildInSameConsole(L"D:child");
++        SetStdHandle(STD_OUTPUT_HANDLE, origBuffer);
++        SetStdHandle(STD_ERROR_HANDLE, origBuffer);
++
++        // At t=6, write again to newBuffer.
++        Sleep(4000);
++        trace("parent:----");
++        writeTest(newBuffer, "TEST PASSED!");
++
++        // At t=8, close the newBuffer.  In earlier versions of windows
++        // (including Server 2008 R2), the console then switches back to
++        // origBuffer.  As of Windows 8, it doesn't, because somehow the child
++        // process is keeping the console on newBuffer, even though the child
++        // process closed its STDIN/STDOUT/STDERR handles.  Killing the child
++        // process by hand after the test finishes *does* force the console
++        // back to origBuffer.
++        Sleep(2000);
++        closeHandle(newBuffer);
++
++        Sleep(120000);
++        return;
++    }
++
++    if (!strcmp(argv[1], "D:child")) {
++        g_prefix = "child: ";
++        // At t=2, the child starts.
++        trace("child:----");
++        dumpHandles();
++        writeTest("writing to newBuffer");
++
++        // At t=4, the child explicitly closes its handle.
++        Sleep(2000);
++        trace("child:----");
++        if (GetStdHandle(STD_ERROR_HANDLE) != GetStdHandle(STD_OUTPUT_HANDLE)) {
++            closeHandle(GetStdHandle(STD_ERROR_HANDLE));
++        }
++        closeHandle(GetStdHandle(STD_OUTPUT_HANDLE));
++        closeHandle(GetStdHandle(STD_INPUT_HANDLE));
++
++        Sleep(120000);
++        return;
++    }
++}
++
++
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        printf("USAGE: %s testnum\n", argv[0]);
++        return 0;
++    }
++
++    if (argv[1][0] == '1') {
++        test1(argc, argv);
++    } else if (argv[1][0] == '2') {
++        test2(argc, argv);
++    } else if (argv[1][0] == 'A') {
++        testA(argc, argv);
++    } else if (argv[1][0] == 'B') {
++        testB(argc, argv);
++    } else if (argv[1][0] == 'C') {
++        testC(argc, argv);
++    } else if (argv[1][0] == 'D') {
++        testD(argc, argv);
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2b648c94093d4fd4e568ecacfdaa5bc0006c2356
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,151 @@@
++#include <windows.h>
++
++#include "TestUtil.cc"
++
++const char *g_prefix = "";
++
++static void dumpHandles() {
++    trace("%sSTDIN=0x%I64x STDOUT=0x%I64x STDERR=0x%I64x",
++        g_prefix,
++        (long long)GetStdHandle(STD_INPUT_HANDLE),
++        (long long)GetStdHandle(STD_OUTPUT_HANDLE),
++        (long long)GetStdHandle(STD_ERROR_HANDLE));
++}
++
++static HANDLE createBuffer() {
++
++    // If sa isn't provided, the handle defaults to not-inheritable.
++    SECURITY_ATTRIBUTES sa = {0};
++    sa.nLength = sizeof(sa);
++    sa.bInheritHandle = TRUE;
++
++    trace("%sCreating a new buffer...", g_prefix);
++    HANDLE conout = CreateConsoleScreenBuffer(
++                GENERIC_READ | GENERIC_WRITE,
++                FILE_SHARE_READ | FILE_SHARE_WRITE,
++                &sa,
++                CONSOLE_TEXTMODE_BUFFER, NULL);
++
++    trace("%sCreating a new buffer... 0x%I64x", g_prefix, (long long)conout);
++    return conout;
++}
++
++static const char *successOrFail(BOOL ret) {
++    return ret ? "ok" : "FAILED";
++}
++
++static void setConsoleActiveScreenBuffer(HANDLE conout) {
++    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called...",
++        g_prefix, (long long)conout);
++    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called... %s",
++        g_prefix, (long long)conout,
++        successOrFail(SetConsoleActiveScreenBuffer(conout)));
++}
++
++static void writeTest(HANDLE conout, const char *msg) {
++    char writeData[256];
++    sprintf(writeData, "%s%s\n", g_prefix, msg);
++
++    trace("%sWriting to 0x%I64x: '%s'...",
++        g_prefix, (long long)conout, msg);
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleA(conout, writeData, strlen(writeData), &actual, NULL);
++    trace("%sWriting to 0x%I64x: '%s'... %s",
++        g_prefix, (long long)conout, msg,
++        successOrFail(ret && actual == strlen(writeData)));
++}
++
++static HANDLE startChildInSameConsole(const wchar_t *args, BOOL
++                                    bInheritHandles=FALSE) {
++    wchar_t program[1024];
++    wchar_t cmdline[1024];
++    GetModuleFileNameW(NULL, program, 1024);
++    swprintf(cmdline, L"\"%ls\" %ls", program, args);
++
++    STARTUPINFOW sui;
++    PROCESS_INFORMATION pi;
++    memset(&sui, 0, sizeof(sui));
++    memset(&pi, 0, sizeof(pi));
++    sui.cb = sizeof(sui);
++
++    CreateProcessW(program, cmdline,
++                   NULL, NULL,
++                   /*bInheritHandles=*/bInheritHandles,
++                   /*dwCreationFlags=*/0,
++                   NULL, NULL,
++                   &sui, &pi);
++
++    return pi.hProcess;
++}
++
++static HANDLE dup(HANDLE h, HANDLE targetProcess) {
++    HANDLE h2 = INVALID_HANDLE_VALUE;
++    BOOL ret = DuplicateHandle(
++        GetCurrentProcess(), h,
++        targetProcess, &h2,
++        0, TRUE, DUPLICATE_SAME_ACCESS);
++    trace("dup(0x%I64x) to process 0x%I64x... %s, 0x%I64x",
++        (long long)h,
++        (long long)targetProcess,
++        successOrFail(ret),
++        (long long)h2);
++    return h2;
++}
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"parent");
++        return 0;
++    }
++
++    if (!strcmp(argv[1], "parent")) {
++        g_prefix = "parent: ";
++        dumpHandles();
++        HANDLE hChild = startChildInSameConsole(L"child");
++
++        // Windows 10.
++        HANDLE orig1 = GetStdHandle(STD_OUTPUT_HANDLE);
++        HANDLE new1 = createBuffer();
++
++        Sleep(2000);
++        setConsoleActiveScreenBuffer(new1);
++
++        // Handle duplication results to child process in same console:
++        //  - Windows XP:                                       fails
++        //  - Windows 7 Ultimate SP1 32-bit:                    fails
++        //  - Windows Server 2008 R2 Datacenter SP1 64-bit:     fails
++        //  - Windows 8 Enterprise 32-bit:                      succeeds
++        //  - Windows 10:                                       succeeds
++        HANDLE orig2 = dup(orig1, GetCurrentProcess());
++        HANDLE new2 = dup(new1, GetCurrentProcess());
++
++        dup(orig1, hChild);
++        dup(new1, hChild);
++
++        // The writes to orig1/orig2 are invisible.  The writes to new1/new2
++        // are visible.
++        writeTest(orig1, "write to orig1");
++        writeTest(orig2, "write to orig2");
++        writeTest(new1, "write to new1");
++        writeTest(new2, "write to new2");
++
++        Sleep(120000);
++        return 0;
++    }
++
++    if (!strcmp(argv[1], "child")) {
++        g_prefix = "child: ";
++        dumpHandles();
++        Sleep(4000);
++        for (unsigned int i = 0x1; i <= 0xB0; ++i) {
++            char msg[256];
++            sprintf(msg, "Write to handle 0x%x", i);
++            HANDLE h = reinterpret_cast<HANDLE>(i);
++            writeTest(h, msg);
++        }
++        Sleep(120000);
++        return 0;
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a6c27739d8007cff6a34a5df1c926f9fe3a474ac
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,45 @@@
++#define _WIN32_WINNT 0x0501
++#include <stdio.h>
++#include <windows.h>
++
++#include "../src/shared/DebugClient.cc"
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
++
++CALLBACK DWORD pausingThread(LPVOID dummy)
++{
++    HWND hwnd = GetConsoleWindow();
++    while (true) {
++        SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0);
++        Sleep(1000);
++        SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
++        Sleep(1000);
++    }
++}
++
++int main()
++{
++    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
++    CONSOLE_SCREEN_BUFFER_INFO info;
++
++    GetConsoleScreenBufferInfo(out, &info);
++    COORD initial = info.dwCursorPosition;
++
++    CreateThread(NULL, 0,
++                 pausingThread, NULL,
++                 0, NULL);
++
++    for (int i = 0; i < 30; ++i) {
++        Sleep(100);
++        GetConsoleScreenBufferInfo(out, &info);
++        if (memcmp(&info.dwCursorPosition, &initial, sizeof(COORD)) != 0) {
++            trace("cursor moved to [%d,%d]",
++                   info.dwCursorPosition.X,
++                   info.dwCursorPosition.Y);
++        } else {
++            trace("cursor in expected position");
++        }
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b50a1f8dc368d9212ac12821cc1c8088a2ed5483
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,32 @@@
++#include <windows.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    if (argc != 3) {
++        printf("Usage: %s x y width height\n", argv[0]);
++        return 1;
++    }
++
++    const HANDLE conout = CreateFileW(L"CONOUT$",
++                                      GENERIC_READ | GENERIC_WRITE,
++                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
++                                      NULL, OPEN_EXISTING, 0, NULL);
++    ASSERT(conout != INVALID_HANDLE_VALUE);
++
++    COORD size = {
++        (short)atoi(argv[1]),
++        (short)atoi(argv[2]),
++    };
++
++    BOOL ret = SetConsoleScreenBufferSize(conout, size);
++    const unsigned lastError = GetLastError();
++    const char *const retStr = ret ? "OK" : "failed";
++    trace("SetConsoleScreenBufferSize ret: %s (LastError=0x%x)", retStr, lastError);
++    printf("SetConsoleScreenBufferSize ret: %s (LastError=0x%x)\n", retStr, lastError);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d20fdbdfc0dfa6415536ffbde94de9cf6bd08c49
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,10 @@@
++#include <windows.h>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    int col = atoi(argv[1]);
++    int row = atoi(argv[2]);
++    setCursorPos(col, row);
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9bcd4b4cc971dd9e0fc18c49edac85018832dbbb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,145 @@@
++#include <windows.h>
++#include <locale.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string>
++
++#include "TestUtil.cc"
++
++#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0]))
++
++// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
++const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // Japanese
++const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // Simplified Chinese
++const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // Traditional Chinese
++const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // Korean
++
++int main() {
++    setlocale(LC_ALL, "");
++    wchar_t *cmdline = GetCommandLineW();
++    int argc = 0;
++    wchar_t **argv = CommandLineToArgvW(cmdline, &argc);
++    const HANDLE conout = openConout();
++
++    if (argc == 1) {
++        cprintf(L"Usage:\n");
++        cprintf(L"  SetFont <index>\n");
++        cprintf(L"  SetFont options\n");
++        cprintf(L"\n");
++        cprintf(L"Options for SetCurrentConsoleFontEx:\n");
++        cprintf(L"  -idx INDEX\n");
++        cprintf(L"  -w WIDTH\n");
++        cprintf(L"  -h HEIGHT\n");
++        cprintf(L"  -family (0xNN|NN)\n");
++        cprintf(L"  -weight (normal|bold|NNN)\n");
++        cprintf(L"  -face FACENAME\n");
++        cprintf(L"  -face-{gothic|simsun|minglight|gulimche) [JP,CN-sim,CN-tra,KR]\n");
++        cprintf(L"  -tt\n");
++        cprintf(L"  -vec\n");
++        cprintf(L"  -vp\n");
++        cprintf(L"  -dev\n");
++        cprintf(L"  -roman\n");
++        cprintf(L"  -swiss\n");
++        cprintf(L"  -modern\n");
++        cprintf(L"  -script\n");
++        cprintf(L"  -decorative\n");
++        return 0;
++    }
++
++    if (isdigit(argv[1][0])) {
++        int index = _wtoi(argv[1]);
++        HMODULE kernel32 = LoadLibraryW(L"kernel32.dll");
++        FARPROC proc = GetProcAddress(kernel32, "SetConsoleFont");
++        if (proc == NULL) {
++            cprintf(L"Couldn't get address of SetConsoleFont\n");
++        } else {
++            BOOL ret = reinterpret_cast<BOOL WINAPI(*)(HANDLE, DWORD)>(proc)(
++                    conout, index);
++            cprintf(L"SetFont returned %d\n", ret);
++        }
++        return 0;
++    }
++
++    CONSOLE_FONT_INFOEX fontex = {0};
++    fontex.cbSize = sizeof(fontex);
++
++    for (int i = 1; i < argc; ++i) {
++        std::wstring arg = argv[i];
++        if (i + 1 < argc) {
++            std::wstring next = argv[i + 1];
++            if (arg == L"-idx") {
++                fontex.nFont = _wtoi(next.c_str());
++                ++i; continue;
++            } else if (arg == L"-w") {
++                fontex.dwFontSize.X = _wtoi(next.c_str());
++                ++i; continue;
++            } else if (arg == L"-h") {
++                fontex.dwFontSize.Y = _wtoi(next.c_str());
++                ++i; continue;
++            } else if (arg == L"-weight") {
++                if (next == L"normal") {
++                    fontex.FontWeight = 400;
++                } else if (next == L"bold") {
++                    fontex.FontWeight = 700;
++                } else {
++                    fontex.FontWeight = _wtoi(next.c_str());
++                }
++                ++i; continue;
++            } else if (arg == L"-face") {
++                wcsncpy(fontex.FaceName, next.c_str(), COUNT_OF(fontex.FaceName));
++                ++i; continue;
++            } else if (arg == L"-family") {
++                fontex.FontFamily = strtol(narrowString(next).c_str(), nullptr, 0);
++                ++i; continue;
++            }
++        }
++        if (arg == L"-tt") {
++            fontex.FontFamily |= TMPF_TRUETYPE;
++        } else if (arg == L"-vec") {
++            fontex.FontFamily |= TMPF_VECTOR;
++        } else if (arg == L"-vp") {
++            // Setting the TMPF_FIXED_PITCH bit actually indicates variable
++            // pitch.
++            fontex.FontFamily |= TMPF_FIXED_PITCH;
++        } else if (arg == L"-dev") {
++            fontex.FontFamily |= TMPF_DEVICE;
++        } else if (arg == L"-roman") {
++            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_ROMAN;
++        } else if (arg == L"-swiss") {
++            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_SWISS;
++        } else if (arg == L"-modern") {
++            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_MODERN;
++        } else if (arg == L"-script") {
++            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_SCRIPT;
++        } else if (arg == L"-decorative") {
++            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_DECORATIVE;
++        } else if (arg == L"-face-gothic") {
++            wcsncpy(fontex.FaceName, kMSGothic, COUNT_OF(fontex.FaceName));
++        } else if (arg == L"-face-simsun") {
++            wcsncpy(fontex.FaceName, kNSimSun, COUNT_OF(fontex.FaceName));
++        } else if (arg == L"-face-minglight") {
++            wcsncpy(fontex.FaceName, kMingLight, COUNT_OF(fontex.FaceName));
++        } else if (arg == L"-face-gulimche") {
++            wcsncpy(fontex.FaceName, kGulimChe, COUNT_OF(fontex.FaceName));
++        } else {
++            cprintf(L"Unrecognized argument: %ls\n", arg.c_str());
++            exit(1);
++        }
++    }
++
++    cprintf(L"Setting to: nFont=%u dwFontSize=(%d,%d) "
++        L"FontFamily=0x%x FontWeight=%u "
++        L"FaceName=\"%ls\"\n",
++        static_cast<unsigned>(fontex.nFont),
++        fontex.dwFontSize.X, fontex.dwFontSize.Y,
++        fontex.FontFamily, fontex.FontWeight,
++        fontex.FaceName);
++
++    BOOL ret = SetCurrentConsoleFontEx(
++        conout,
++        FALSE,
++        &fontex);
++    cprintf(L"SetCurrentConsoleFontEx returned %d\n", ret);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6291dd674597471325891d60a31edb677049cca5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,36 @@@
++#include <windows.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    if (argc != 5) {
++        printf("Usage: %s x y width height\n", argv[0]);
++        return 1;
++    }
++
++    const HANDLE conout = CreateFileW(L"CONOUT$",
++                                      GENERIC_READ | GENERIC_WRITE,
++                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
++                                      NULL, OPEN_EXISTING, 0, NULL);
++    ASSERT(conout != INVALID_HANDLE_VALUE);
++
++    SMALL_RECT sr = {
++        (short)atoi(argv[1]),
++        (short)atoi(argv[2]),
++        (short)(atoi(argv[1]) + atoi(argv[3]) - 1),
++        (short)(atoi(argv[2]) + atoi(argv[4]) - 1),
++    };
++
++    trace("Calling SetConsoleWindowInfo with {L=%d,T=%d,R=%d,B=%d}",
++        sr.Left, sr.Top, sr.Right, sr.Bottom);
++    BOOL ret = SetConsoleWindowInfo(conout, TRUE, &sr);
++    const unsigned lastError = GetLastError();
++    const char *const retStr = ret ? "OK" : "failed";
++    trace("SetConsoleWindowInfo ret: %s (LastError=0x%x)", retStr, lastError);
++    printf("SetConsoleWindowInfo ret: %s (LastError=0x%x)\n", retStr, lastError);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..29a0f0913162ca5649165f64733c52eb883dcd8e
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,12 @@@
++// This test program is useful for studying commandline<->argv conversion.
++
++#include <stdio.h>
++#include <windows.h>
++
++int main(int argc, char **argv)
++{
++    printf("cmdline = [%s]\n", GetCommandLine());
++    for (int i = 0; i < argc; ++i)
++        printf("[%s]\n", argv[i]);
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..75fbfb81f10715795423d1e99eb58ee5309c4bd0
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,40 @@@
++#include <windows.h>
++#include <stdio.h>
++#include <ctype.h>
++
++int main(int argc, char *argv[])
++{
++    static int escCount = 0;
++
++    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
++    while (true) {
++        DWORD count;
++        INPUT_RECORD ir;
++        if (!ReadConsoleInput(hStdin, &ir, 1, &count)) {
++            printf("ReadConsoleInput failed\n");
++            return 1;
++        }
++
++        if (true) {
++            DWORD mode;
++            GetConsoleMode(hStdin, &mode);
++            SetConsoleMode(hStdin, mode & ~ENABLE_PROCESSED_INPUT);
++        }
++
++        if (ir.EventType == KEY_EVENT) {
++            const KEY_EVENT_RECORD &ker = ir.Event.KeyEvent;
++            printf("%s", ker.bKeyDown ? "dn" : "up");
++            printf(" ch=");
++            if (isprint(ker.uChar.AsciiChar))
++                printf("'%c'", ker.uChar.AsciiChar);
++            printf("%d", ker.uChar.AsciiChar);
++            printf(" vk=%#x", ker.wVirtualKeyCode);
++            printf(" scan=%#x", ker.wVirtualScanCode);
++            printf(" state=%#x", (int)ker.dwControlKeyState);
++            printf(" repeat=%d", ker.wRepeatCount);
++            printf("\n");
++            if (ker.uChar.AsciiChar == 27 && ++escCount == 6)
++                break;
++        }
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9d1796af375f1f2feecda5ba2ce97835b7508dce
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,5 @@@
++#!/usr/bin/env python
++i = 0;
++while True:
++    i += 1
++    print(i)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c832a12b858219583ce5f557af28b3da38c87f48
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,172 @@@
++// This file is included into test programs using #include
++
++#include <windows.h>
++#include <assert.h>
++#include <stdio.h>
++#include <string.h>
++#include <wchar.h>
++#include <vector>
++#include <string>
++
++#include "../src/shared/DebugClient.h"
++#include "../src/shared/TimeMeasurement.h"
++
++#include "../src/shared/DebugClient.cc"
++#include "../src/shared/WinptyAssert.cc"
++#include "../src/shared/WinptyException.cc"
++
++// Launch this test program again, in a new console that we will destroy.
++static void startChildProcess(const wchar_t *args) {
++    wchar_t program[1024];
++    wchar_t cmdline[1024];
++    GetModuleFileNameW(NULL, program, 1024);
++    swprintf(cmdline, L"\"%ls\" %ls", program, args);
++
++    STARTUPINFOW sui;
++    PROCESS_INFORMATION pi;
++    memset(&sui, 0, sizeof(sui));
++    memset(&pi, 0, sizeof(pi));
++    sui.cb = sizeof(sui);
++
++    CreateProcessW(program, cmdline,
++                   NULL, NULL,
++                   /*bInheritHandles=*/FALSE,
++                   /*dwCreationFlags=*/CREATE_NEW_CONSOLE,
++                   NULL, NULL,
++                   &sui, &pi);
++}
++
++static void setBufferSize(HANDLE conout, int x, int y) {
++    COORD size = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
++    BOOL success = SetConsoleScreenBufferSize(conout, size);
++    trace("setBufferSize: (%d,%d), result=%d", x, y, success);
++}
++
++static void setWindowPos(HANDLE conout, int x, int y, int w, int h) {
++    SMALL_RECT r = {
++        static_cast<SHORT>(x), static_cast<SHORT>(y),
++        static_cast<SHORT>(x + w - 1),
++        static_cast<SHORT>(y + h - 1)
++    };
++    BOOL success = SetConsoleWindowInfo(conout, /*bAbsolute=*/TRUE, &r);
++    trace("setWindowPos: (%d,%d,%d,%d), result=%d", x, y, w, h, success);
++}
++
++static void setCursorPos(HANDLE conout, int x, int y) {
++    COORD coord = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
++    SetConsoleCursorPosition(conout, coord);
++}
++
++static void setBufferSize(int x, int y) {
++    setBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), x, y);
++}
++
++static void setWindowPos(int x, int y, int w, int h) {
++    setWindowPos(GetStdHandle(STD_OUTPUT_HANDLE), x, y, w, h);
++}
++
++static void setCursorPos(int x, int y) {
++    setCursorPos(GetStdHandle(STD_OUTPUT_HANDLE), x, y);
++}
++
++static void countDown(int sec) {
++    for (int i = sec; i > 0; --i) {
++        printf("%d.. ", i);
++        fflush(stdout);
++        Sleep(1000);
++    }
++    printf("\n");
++}
++
++static void writeBox(int x, int y, int w, int h, char ch, int attributes=7) {
++    CHAR_INFO info = { 0 };
++    info.Char.AsciiChar = ch;
++    info.Attributes = attributes;
++    std::vector<CHAR_INFO> buf(w * h, info);
++    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++    COORD bufSize = { static_cast<SHORT>(w), static_cast<SHORT>(h) };
++    COORD bufCoord = { 0, 0 };
++    SMALL_RECT writeRegion = {
++        static_cast<SHORT>(x),
++        static_cast<SHORT>(y),
++        static_cast<SHORT>(x + w - 1),
++        static_cast<SHORT>(y + h - 1)
++    };
++    WriteConsoleOutputA(conout, buf.data(), bufSize, bufCoord, &writeRegion);
++}
++
++static void setChar(int x, int y, char ch, int attributes=7) {
++    writeBox(x, y, 1, 1, ch, attributes);
++}
++
++static void fillChar(int x, int y, int repeat, char ch) {
++    COORD coord = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
++    DWORD actual = 0;
++    FillConsoleOutputCharacterA(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        ch, repeat, coord, &actual);
++}
++
++static void repeatChar(int count, char ch) {
++    for (int i = 0; i < count; ++i) {
++        putchar(ch);
++    }
++    fflush(stdout);
++}
++
++// I don't know why, but wprintf fails to print this face name,
++// "MS ゴシック" (aka MS Gothic).  It helps to use wprintf instead of printf, and
++// it helps to call `setlocale(LC_ALL, "")`, but the Japanese symbols are
++// ultimately converted to `?` symbols, even though MS Gothic is able to
++// display its own name, and the current code page is 932 (Shift-JIS).
++static void cvfprintf(HANDLE conout, const wchar_t *fmt, va_list ap) {
++    wchar_t buffer[256];
++    vswprintf(buffer, 256 - 1, fmt, ap);
++    buffer[255] = L'\0';
++    DWORD actual = 0;
++    if (!WriteConsoleW(conout, buffer, wcslen(buffer), &actual, NULL)) {
++        wprintf(L"WriteConsoleW call failed!\n");
++    }
++}
++
++static void cfprintf(HANDLE conout, const wchar_t *fmt, ...) {
++    va_list ap;
++    va_start(ap, fmt);
++    cvfprintf(conout, fmt, ap);
++    va_end(ap);
++}
++
++static void cprintf(const wchar_t *fmt, ...) {
++    va_list ap;
++    va_start(ap, fmt);
++    cvfprintf(GetStdHandle(STD_OUTPUT_HANDLE), fmt, ap);
++    va_end(ap);
++}
++
++static std::string narrowString(const std::wstring &input)
++{
++    int mblen = WideCharToMultiByte(
++        CP_UTF8, 0,
++        input.data(), input.size(),
++        NULL, 0, NULL, NULL);
++    if (mblen <= 0) {
++        return std::string();
++    }
++    std::vector<char> tmp(mblen);
++    int mblen2 = WideCharToMultiByte(
++        CP_UTF8, 0,
++        input.data(), input.size(),
++        tmp.data(), tmp.size(),
++        NULL, NULL);
++    assert(mblen2 == mblen);
++    return std::string(tmp.data(), tmp.size());
++}
++
++HANDLE openConout() {
++    const HANDLE conout = CreateFileW(L"CONOUT$",
++                                      GENERIC_READ | GENERIC_WRITE,
++                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
++                                      NULL, OPEN_EXISTING, 0, NULL);
++    ASSERT(conout != INVALID_HANDLE_VALUE);
++    return conout;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7210d410323e75238b4a8a51084d835ff6053d45
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,102 @@@
++// Demonstrates how U+30FC is sometimes handled as a single-width character
++// when it should be handled as a double-width character.
++//
++// It only runs on computers where 932 is a valid code page.  Set the system
++// local to "Japanese (Japan)" to ensure this.
++//
++// The problem seems to happen when U+30FC is printed in a console using the
++// Lucida Console font, and only when that font is at certain sizes.
++//
++
++#include <windows.h>
++#include <assert.h>
++#include <locale.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include "TestUtil.cc"
++
++#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
++
++static void setFont(const wchar_t *faceName, int pxSize) {
++    CONSOLE_FONT_INFOEX infoex = {0};
++    infoex.cbSize = sizeof(infoex);
++    infoex.dwFontSize.Y = pxSize;
++    wcsncpy(infoex.FaceName, faceName, COUNT_OF(infoex.FaceName));
++    BOOL ret = SetCurrentConsoleFontEx(
++        GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &infoex);
++    assert(ret);
++}
++
++static bool performTest(const wchar_t testChar) {
++    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    SetConsoleTextAttribute(conout, 7);
++
++    system("cls");
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleW(conout, &testChar, 1, &actual, NULL);
++    assert(ret && actual == 1);
++
++    CHAR_INFO verify[2];
++    COORD bufSize = {2, 1};
++    COORD bufCoord = {0, 0};
++    const SMALL_RECT readRegion = {0, 0, 1, 0};
++    SMALL_RECT actualRegion = readRegion;
++    ret = ReadConsoleOutputW(conout, verify, bufSize, bufCoord, &actualRegion);
++    assert(ret && !memcmp(&readRegion, &actualRegion, sizeof(readRegion)));
++    assert(verify[0].Char.UnicodeChar == testChar);
++
++    if (verify[1].Char.UnicodeChar == testChar) {
++        // Typical double-width behavior with a TrueType font.  Pass.
++        assert(verify[0].Attributes == 0x107);
++        assert(verify[1].Attributes == 0x207);
++        return true;
++    } else if (verify[1].Char.UnicodeChar == 0) {
++        // Typical double-width behavior with a Raster Font.  Pass.
++        assert(verify[0].Attributes == 7);
++        assert(verify[1].Attributes == 0);
++        return true;
++    } else if (verify[1].Char.UnicodeChar == L' ') {
++        // Single-width behavior.  Fail.
++        assert(verify[0].Attributes == 7);
++        assert(verify[1].Attributes == 7);
++        return false;
++    } else {
++        // Unexpected output.
++        assert(false);
++    }
++}
++
++int main(int argc, char *argv[]) {
++    setlocale(LC_ALL, "");
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    assert(SetConsoleCP(932));
++    assert(SetConsoleOutputCP(932));
++
++    const wchar_t testChar = 0x30FC;
++    const wchar_t *const faceNames[] = {
++        L"Lucida Console",
++        L"Consolas",
++        L"MS ゴシック",
++    };
++
++    trace("Test started");
++
++    for (auto faceName : faceNames) {
++        for (int px = 1; px <= 50; ++px) {
++            setFont(faceName, px);
++            if (!performTest(testChar)) {
++                trace("FAILURE: %s %dpx", narrowString(faceName).c_str(), px);
++            }
++        }
++    }
++
++    trace("Test complete");
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a8d798e70dde3e20168eb4729d3b95afa10f7452
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,246 @@@
++#include <windows.h>
++
++#include <assert.h>
++#include <vector>
++
++#include "TestUtil.cc"
++
++#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
++
++
++CHAR_INFO ci(wchar_t ch, WORD attributes) {
++    CHAR_INFO ret;
++    ret.Char.UnicodeChar = ch;
++    ret.Attributes = attributes;
++    return ret;
++}
++
++CHAR_INFO ci(wchar_t ch) {
++    return ci(ch, 7);
++}
++
++CHAR_INFO ci() {
++    return ci(L' ');
++}
++
++bool operator==(SMALL_RECT x, SMALL_RECT y) {
++    return !memcmp(&x, &y, sizeof(x));
++}
++
++SMALL_RECT sr(COORD pt, COORD size) {
++    return {
++        pt.X, pt.Y,
++        static_cast<SHORT>(pt.X + size.X - 1),
++        static_cast<SHORT>(pt.Y + size.Y - 1)
++    };
++}
++
++static void set(
++        const COORD pt,
++        const COORD size,
++        const std::vector<CHAR_INFO> &data) {
++    assert(data.size() == size.X * size.Y);
++    SMALL_RECT writeRegion = sr(pt, size);
++    BOOL ret = WriteConsoleOutputW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        data.data(), size, {0, 0}, &writeRegion);
++    assert(ret && writeRegion == sr(pt, size));
++}
++
++static void set(
++        const COORD pt,
++        const std::vector<CHAR_INFO> &data) {
++    set(pt, {static_cast<SHORT>(data.size()), 1}, data);
++}
++
++static void writeAttrsAt(
++        const COORD pt,
++        const std::vector<WORD> &data) {
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleOutputAttribute(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        data.data(), data.size(), pt, &actual);
++    assert(ret && actual == data.size());
++}
++
++static void writeCharsAt(
++        const COORD pt,
++        const std::vector<wchar_t> &data) {
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleOutputCharacterW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        data.data(), data.size(), pt, &actual);
++    assert(ret && actual == data.size());
++}
++
++static void writeChars(
++        const std::vector<wchar_t> &data) {
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        data.data(), data.size(), &actual, NULL);
++    assert(ret && actual == data.size());
++}
++
++std::vector<CHAR_INFO> get(
++        const COORD pt,
++        const COORD size) {
++    std::vector<CHAR_INFO> data(size.X * size.Y);
++    SMALL_RECT readRegion = sr(pt, size);
++    BOOL ret = ReadConsoleOutputW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        data.data(), size, {0, 0}, &readRegion);
++    assert(ret && readRegion == sr(pt, size));
++    return data;
++}
++
++std::vector<wchar_t> readCharsAt(
++        const COORD pt,
++        int size) {
++    std::vector<wchar_t> data(size);
++    DWORD actual = 0;
++    BOOL ret = ReadConsoleOutputCharacterW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        data.data(), data.size(), pt, &actual);
++    assert(ret);
++    data.resize(actual); // With double-width chars, we can read fewer than `size`.
++    return data;
++}
++
++static void dump(const COORD pt, const COORD size) {
++    for (CHAR_INFO ci : get(pt, size)) {
++        printf("%04X %04X\n", ci.Char.UnicodeChar, ci.Attributes);
++    }
++}
++
++static void dumpCharsAt(const COORD pt, int size) {
++    for (wchar_t ch : readCharsAt(pt, size)) {
++        printf("%04X\n", ch);
++    }
++}
++
++static COORD getCursorPos() {
++    CONSOLE_SCREEN_BUFFER_INFO info = { sizeof(info) };
++    assert(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info));
++    return info.dwCursorPosition;
++}
++
++static void test1() {
++    // We write "䀀䀀", then write "䀁" in the middle of the two.  The second
++    // write turns the first and last cells into spaces.  The LEADING/TRAILING
++    // flags retain consistency.
++    printf("test1 - overlap full-width char with full-width char\n");
++    writeCharsAt({1,0}, {0x4000, 0x4000});
++    dump({0,0}, {6,1});
++    printf("\n");
++    writeCharsAt({2,0}, {0x4001});
++    dump({0,0}, {6,1});
++    printf("\n");
++}
++
++static void test2() {
++    // Like `test1`, but use a lower-level API to do the write.  Consistency is
++    // preserved here too -- the first and last cells are replaced with spaces.
++    printf("test2 - overlap full-width char with full-width char (lowlevel)\n");
++    writeCharsAt({1,0}, {0x4000, 0x4000});
++    dump({0,0}, {6,1});
++    printf("\n");
++    set({2,0}, {ci(0x4001,0x107), ci(0x4001,0x207)});
++    dump({0,0}, {6,1});
++    printf("\n");
++}
++
++static void test3() {
++    // However, the lower-level API can break the LEADING/TRAILING invariant
++    // explicitly:
++    printf("test3 - explicitly violate LEADING/TRAILING using lowlevel API\n");
++    set({1,0}, {
++        ci(0x4000, 0x207),
++        ci(0x4001, 0x107),
++        ci(0x3044, 7),
++        ci(L'X', 0x107),
++        ci(L'X', 0x207),
++    });
++    dump({0,0}, {7,1});
++}
++
++static void test4() {
++    // It is possible for the two cells of a double-width character to have two
++    // colors.
++    printf("test4 - use lowlevel to assign two colors to one full-width char\n");
++    set({0,0}, {
++        ci(0x4000, 0x142),
++        ci(0x4000, 0x224),
++    });
++    dump({0,0}, {2,1});
++}
++
++static void test5() {
++    // WriteConsoleOutputAttribute doesn't seem to affect the LEADING/TRAILING
++    // flags.
++    printf("test5 - WriteConsoleOutputAttribute cannot affect LEADING/TRAILING\n");
++
++    // Trying to clear the flags doesn't work...
++    writeCharsAt({0,0}, {0x4000});
++    dump({0,0}, {2,1});
++    writeAttrsAt({0,0}, {0x42, 0x24});
++    printf("\n");
++    dump({0,0}, {2,1});
++
++    // ... and trying to add them also doesn't work.
++    writeCharsAt({0,1}, {'A', ' '});
++    writeAttrsAt({0,1}, {0x107, 0x207});
++    printf("\n");
++    dump({0,1}, {2,1});
++}
++
++static void test6() {
++    // The cursor position may be on either cell of a double-width character.
++    // Visually, the cursor appears under both cells, regardless of which
++    // specific one has the cursor.
++    printf("test6 - cursor can be either left or right cell of full-width char\n");
++
++    writeCharsAt({2,1}, {0x4000});
++
++    setCursorPos(2, 1);
++    auto pos1 = getCursorPos();
++    Sleep(1000);
++
++    setCursorPos(3, 1);
++    auto pos2 = getCursorPos();
++    Sleep(1000);
++
++    setCursorPos(0, 15);
++    printf("%d,%d\n", pos1.X, pos1.Y);
++    printf("%d,%d\n", pos2.X, pos2.Y);
++}
++
++static void runTest(void (&test)()) {
++    system("cls");
++    setCursorPos(0, 14);
++    test();
++    system("pause");
++}
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(80, 40);
++    setWindowPos(0, 0, 80, 40);
++
++    auto cp = GetConsoleOutputCP();
++    assert(cp == 932 || cp == 936 || cp == 949 || cp == 950);
++
++    runTest(test1);
++    runTest(test2);
++    runTest(test3);
++    runTest(test4);
++    runTest(test5);
++    runTest(test6);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..05f80f70bd138cf580f009086d537045c79930eb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,130 @@@
++//
++// Test half-width vs full-width characters.
++//
++
++#include <windows.h>
++#include <assert.h>
++#include <stdlib.h>
++#include <stdio.h>
++
++#include "TestUtil.cc"
++
++static void writeChars(const wchar_t *text) {
++    wcslen(text);
++    const int len = wcslen(text);
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        text, len, &actual, NULL);
++    trace("writeChars: ret=%d, actual=%lld", ret, (long long)actual);
++}
++
++static void dumpChars(int x, int y, int w, int h) {
++    BOOL ret;
++    const COORD bufSize = {w, h};
++    const COORD bufCoord = {0, 0};
++    const SMALL_RECT topLeft = {x, y, x + w - 1, y + h - 1};
++    CHAR_INFO mbcsData[w * h];
++    CHAR_INFO unicodeData[w * h];
++    SMALL_RECT readRegion;
++    readRegion = topLeft;
++    ret = ReadConsoleOutputW(GetStdHandle(STD_OUTPUT_HANDLE), unicodeData,
++                             bufSize, bufCoord, &readRegion);
++    assert(ret);
++    readRegion = topLeft;
++    ret = ReadConsoleOutputA(GetStdHandle(STD_OUTPUT_HANDLE), mbcsData,
++                             bufSize, bufCoord, &readRegion);
++    assert(ret);
++
++    printf("\n");
++    for (int i = 0; i < w * h; ++i) {
++        printf("(%02d,%02d) CHAR: %04x %4x -- %02x %4x\n",
++            x + i % w, y + i / w,
++            (unsigned short)unicodeData[i].Char.UnicodeChar,
++            (unsigned short)unicodeData[i].Attributes,
++            (unsigned char)mbcsData[i].Char.AsciiChar,
++            (unsigned short)mbcsData[i].Attributes);
++    }
++}
++
++int main(int argc, char *argv[]) {
++    system("cls");
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(80, 38);
++    setWindowPos(0, 0, 80, 38);
++
++    // Write text.
++    const wchar_t text1[] = {
++        0x3044, // U+3044 (HIRAGANA LETTER I)
++        0x2014, // U+2014 (EM DASH)
++        0x3044, // U+3044 (HIRAGANA LETTER I)
++        0xFF2D, // U+FF2D (FULLWIDTH LATIN CAPITAL LETTER M)
++        0x30FC, // U+30FC (KATAKANA-HIRAGANA PROLONGED SOUND MARK)
++        0x0031, // U+3031 (DIGIT ONE)
++        0x2014, // U+2014 (EM DASH)
++        0x0032, // U+0032 (DIGIT TWO)
++        0x005C, // U+005C (REVERSE SOLIDUS)
++        0x3044, // U+3044 (HIRAGANA LETTER I)
++        0
++    };
++    setCursorPos(0, 0);
++    writeChars(text1);
++
++    setCursorPos(78, 1);
++    writeChars(L"<>");
++
++    const wchar_t text2[] = {
++        0x0032, // U+3032 (DIGIT TWO)
++        0x3044, // U+3044 (HIRAGANA LETTER I)
++        0,
++    };
++    setCursorPos(78, 1);
++    writeChars(text2);
++
++    system("pause");
++
++    dumpChars(0, 0, 17, 1);
++    dumpChars(2, 0, 2, 1);
++    dumpChars(2, 0, 1, 1);
++    dumpChars(3, 0, 1, 1);
++    dumpChars(78, 1, 2, 1);
++    dumpChars(0, 2, 2, 1);
++
++    system("pause");
++    system("cls");
++
++    const wchar_t text3[] = {
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 1
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 2
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 3
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 4
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 5
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 6
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 7
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 8
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 9
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 10
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 11
++        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 12
++        L'\r', '\n',
++        L'\r', '\n',
++        0
++    };
++    writeChars(text3);
++    system("pause");
++    {
++        const COORD bufSize = {80, 2};
++        const COORD bufCoord = {0, 0};
++        SMALL_RECT readRegion = {0, 0, 79, 1};
++        CHAR_INFO unicodeData[160];
++        BOOL ret = ReadConsoleOutputW(GetStdHandle(STD_OUTPUT_HANDLE), unicodeData,
++                                 bufSize, bufCoord, &readRegion);
++        assert(ret);
++        for (int i = 0; i < 96; ++i) {
++            printf("%04x ", unicodeData[i].Char.UnicodeChar);
++        }
++        printf("\n");
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..372e0451574691ad264d04575f3b99257ec83749
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,89 @@@
++/*
++ * Unix test code that puts the terminal into raw mode, then echos typed
++ * characters to stdout.  Derived from sample code in the Stevens book, posted
++ * online at http://www.lafn.org/~dave/linux/terminalIO.html.
++ */
++
++#include <termios.h>
++#include <unistd.h>
++#include <stdlib.h>
++#include <stdio.h>
++#include "FormatChar.h"
++
++static struct termios   save_termios;
++static int              term_saved;
++
++/* RAW! mode */
++int tty_raw(int fd)
++{
++    struct termios  buf;
++
++    if (tcgetattr(fd, &save_termios) < 0) /* get the original state */
++        return -1;
++
++    buf = save_termios;
++
++    /* echo off, canonical mode off, extended input
++       processing off, signal chars off */
++    buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
++
++    /* no SIGINT on BREAK, CR-to-NL off, input parity
++       check off, don't strip the 8th bit on input,
++       ouput flow control off */
++    buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
++
++    /* clear size bits, parity checking off */
++    buf.c_cflag &= ~(CSIZE | PARENB);
++
++    /* set 8 bits/char */
++    buf.c_cflag |= CS8;
++
++    /* output processing off */
++    buf.c_oflag &= ~(OPOST);
++
++    buf.c_cc[VMIN] = 1;  /* 1 byte at a time */
++    buf.c_cc[VTIME] = 0; /* no timer on input */
++
++    if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
++        return -1;
++
++    term_saved = 1;
++
++    return 0;
++}
++
++
++/* set it to normal! */
++int tty_reset(int fd)
++{
++    if (term_saved)
++        if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)
++            return -1;
++
++    return 0;
++}
++
++
++int main()
++{
++    tty_raw(0);
++
++    int count = 0;
++    while (true) {
++        char ch;
++        char buf[16];
++        int actual = read(0, &ch, 1);
++        if (actual != 1) {
++            perror("read error");
++            break;
++        }
++        formatChar(buf, ch);
++        fputs(buf, stdout);
++        fflush(stdout);
++        if (ch == 3) // Ctrl-C
++            break;
++    }
++
++    tty_reset(0);
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ef5f302de47977f67980ce318989b53483d81e6b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,46 @@@
++#include <windows.h>
++#include <assert.h>
++#include <stdlib.h>
++#include <stdio.h>
++
++#include <vector>
++#include <string>
++
++int main(int argc, char *argv[]) {
++    system("cls");
++
++    if (argc == 1) {
++        printf("Usage: %s hhhh\n", argv[0]);
++        return 0;
++    }
++
++    std::wstring dataToWrite;
++    for (int i = 1; i < argc; ++i) {
++        wchar_t ch = strtol(argv[i], NULL, 16);
++        dataToWrite.push_back(ch);
++    }
++
++    DWORD actual = 0;
++    BOOL ret = WriteConsoleW(
++        GetStdHandle(STD_OUTPUT_HANDLE),
++        dataToWrite.data(), dataToWrite.size(), &actual, NULL);
++    assert(ret && actual == dataToWrite.size());
++
++    // Read it back.
++    std::vector<CHAR_INFO> readBuffer(dataToWrite.size() * 2);
++    COORD bufSize = {static_cast<short>(readBuffer.size()), 1};
++    COORD bufCoord = {0, 0};
++    SMALL_RECT topLeft = {0, 0, static_cast<short>(readBuffer.size() - 1), 0};
++    ret = ReadConsoleOutputW(
++            GetStdHandle(STD_OUTPUT_HANDLE), readBuffer.data(),
++            bufSize, bufCoord, &topLeft);
++    assert(ret);
++
++    printf("\n");
++    for (int i = 0; i < readBuffer.size(); ++i) {
++        printf("CHAR: %04x %04x\n",
++            readBuffer[i].Char.UnicodeChar,
++            readBuffer[i].Attributes);
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..58f0897022e17a3934db164640389e369ab574b4
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,122 @@@
++//
++// 2015-09-25
++// I measured these limits on the size of a single ReadConsoleOutputW call.
++// The limit seems to more-or-less disppear with Windows 8, which is the first
++// OS to stop using ALPCs for console I/O.  My guess is that the new I/O
++// method does not use the 64KiB shared memory buffer that the ALPC method
++// uses.
++//
++// I'm guessing the remaining difference between Windows 8/8.1 and Windows 10
++// might be related to the 32-vs-64-bitness.
++//
++// Client OSs
++//
++// Windows XP 32-bit VM ==> up to 13304 characters
++//  - 13304x1 works, but 13305x1 fails instantly
++// Windows 7 32-bit VM ==> between 16-17 thousand characters
++//  - 16000x1 works, 17000x1 fails instantly
++//  - 163x100 *crashes* conhost.exe but leaves VeryLargeRead.exe running
++// Windows 8 32-bit VM ==> between 240-250 million characters
++//  - 10000x24000 works, but 10000x25000 does not
++// Windows 8.1 32-bit VM ==> between 240-250 million characters
++//  - 10000x24000 works, but 10000x25000 does not
++// Windows 10 64-bit VM ==> no limit (tested to 576 million characters)
++//  - 24000x24000 works
++//  - `ver` reports [Version 10.0.10240], conhost.exe and ConhostV1.dll are
++//    10.0.10240.16384 for file and product version.  ConhostV2.dll is
++//    10.0.10240.16391 for file and product version.
++//
++// Server OSs
++//
++// Windows Server 2008 64-bit VM ==> 14300-14400 characters
++//  - 14300x1 works, 14400x1 fails instantly
++//  - This OS does not have conhost.exe.
++//  - `ver` reports [Version 6.0.6002]
++// Windows Server 2008 R2 64-bit VM ==> 15600-15700 characters
++//  - 15600x1 works, 15700x1 fails instantly
++//  - This OS has conhost.exe, and procexp.exe reveals console ALPC ports in
++//    use in conhost.exe.
++//  - `ver` reports [Version 6.1.7601], conhost.exe is 6.1.7601.23153 for file
++//    and product version.
++// Windows Server 2012 64-bit VM ==> at least 100 million characters
++//  - 10000x10000 works (VM had only 1GiB of RAM, so I skipped larger tests)
++//  - This OS has Windows 8's task manager and procexp.exe reveals the same
++//    lack of ALPC ports and the same \Device\ConDrv\* files as Windows 8.
++//  - `ver` reports [Version 6.2.9200], conhost.exe is 6.2.9200.16579 for file
++//    and product version.
++//
++// To summarize:
++//
++// client-OS    server-OS               notes
++// ---------------------------------------------------------------------------
++// XP           Server 2008             CSRSS, small reads
++// 7            Server 2008 R2          ALPC-to-conhost, small reads
++// 8, 8.1       Server 2012             new I/O interface, large reads allowed
++// 10           <no server OS yet>      enhanced console w/rewrapping
++//
++// (Presumably, Win2K, Vista, and Win2K3 behave the same as XP.  conhost.exe
++// was announced as a Win7 feature.)
++//
++
++#include <windows.h>
++#include <assert.h>
++#include <vector>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    long long width = 9000;
++    long long height = 9000;
++
++    assert(argc >= 1);
++    if (argc == 4) {
++        width = atoi(argv[2]);
++        height = atoi(argv[3]);
++    } else {
++        if (argc == 3) {
++            width = atoi(argv[1]);
++            height = atoi(argv[2]);
++        }
++        wchar_t args[1024];
++        swprintf(args, 1024, L"CHILD %lld %lld", width, height);
++        startChildProcess(args);
++        return 0;
++    }
++
++    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(width, height);
++    setWindowPos(0, 0, std::min(80LL, width), std::min(50LL, height));
++
++    setCursorPos(0, 0);
++    printf("A");
++    fflush(stdout);
++    setCursorPos(width - 2, height - 1);
++    printf("B");
++    fflush(stdout);
++
++    trace("sizeof(CHAR_INFO) = %d", (int)sizeof(CHAR_INFO));
++
++    trace("Allocating buffer...");
++    CHAR_INFO *buffer = new CHAR_INFO[width * height];
++    assert(buffer != NULL);
++    memset(&buffer[0], 0, sizeof(CHAR_INFO));
++    memset(&buffer[width * height - 2], 0, sizeof(CHAR_INFO));
++
++    COORD bufSize = { width, height };
++    COORD bufCoord = { 0, 0 };
++    SMALL_RECT readRegion = { 0, 0, width - 1, height - 1 };
++    trace("ReadConsoleOutputW: calling...");
++    BOOL success = ReadConsoleOutputW(conout, buffer, bufSize, bufCoord, &readRegion);
++    trace("ReadConsoleOutputW: success=%d", success);
++
++    assert(buffer[0].Char.UnicodeChar == L'A');
++    assert(buffer[width * height - 2].Char.UnicodeChar == L'B');
++    trace("Top-left and bottom-right characters read successfully!");
++
++    Sleep(30000);
++
++    delete [] buffer;
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..97bf59f998ba319cd5ac3152ce543785af0f6172
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,56 @@@
++/*
++ * Sending VK_PAUSE to the console window almost works as a mechanism for
++ * pausing it, but it doesn't because the console could turn off the
++ * ENABLE_LINE_INPUT console mode flag.
++ */
++
++#define _WIN32_WINNT 0x0501
++#include <stdio.h>
++#include <stdlib.h>
++#include <windows.h>
++
++CALLBACK DWORD pausingThread(LPVOID dummy)
++{
++    if (1) {
++        Sleep(1000);
++        HWND hwnd = GetConsoleWindow();
++        SendMessage(hwnd, WM_KEYDOWN, VK_PAUSE, 1);
++        Sleep(1000);
++        SendMessage(hwnd, WM_KEYDOWN, VK_ESCAPE, 1);
++    }
++
++    if (0) {
++        INPUT_RECORD ir;
++        memset(&ir, 0, sizeof(ir));
++        ir.EventType = KEY_EVENT;
++        ir.Event.KeyEvent.bKeyDown = TRUE;
++        ir.Event.KeyEvent.wVirtualKeyCode = VK_PAUSE;
++        ir.Event.KeyEvent.wRepeatCount = 1;
++    }
++
++    return 0;
++}
++
++int main()
++{
++    HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
++    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
++    COORD c = { 0, 0 };
++
++    DWORD mode;
++    GetConsoleMode(hin, &mode);
++    SetConsoleMode(hin, mode &
++                   ~(ENABLE_LINE_INPUT));
++
++    CreateThread(NULL, 0,
++                 pausingThread, NULL,
++                 0, NULL);
++
++    int i = 0;
++    while (true) {
++        Sleep(100);
++        printf("%d\n", ++i);
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..82feaf3c5016e3dd9dea62d32a2b1f4be92a709f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,52 @@@
++/*
++ * Demonstrates a conhost hang that occurs when widening the console buffer
++ * while selection is in progress.  The problem affects the new Windows 10
++ * console, not the "legacy" console mode that Windows 10 also includes.
++ *
++ * First tested with:
++ *  - Windows 10.0.10240
++ *  - conhost.exe version 10.0.10240.16384
++ *  - ConhostV1.dll version 10.0.10240.16384
++ *  - ConhostV2.dll version 10.0.10240.16391
++ */
++
++#include <windows.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <wchar.h>
++
++#include "TestUtil.cc"
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(80, 25);
++    setWindowPos(0, 0, 80, 25);
++
++    countDown(5);
++
++    SendMessage(GetConsoleWindow(), WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0);
++    Sleep(2000);
++
++    // This API call does not return.  In the console window, the "Select All"
++    // operation appears to end.  The console window becomes non-responsive,
++    // and the conhost.exe process must be killed from the Task Manager.
++    // (Killing this test program or closing the console window is not
++    // sufficient.)
++    //
++    // The same hang occurs whether line resizing is off or on.  It happens
++    // with both "Mark" and "Select All".  Calling setBufferSize with the
++    // existing buffer size does not hang, but calling it with only a changed
++    // buffer height *does* hang.  Calling setWindowPos does not hang.
++    setBufferSize(120, 25);
++
++    printf("Done...\n");
++    Sleep(2000);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..645fa95d5428810429fd7cd99f54aba8f0eb2f09
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,57 @@@
++/*
++ * Demonstrates some wrapping behaviors of the new Windows 10 console.
++ */
++
++#include <windows.h>
++#include <stdio.h>
++#include <stdlib.h>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(40, 20);
++    setWindowPos(0, 0, 40, 20);
++
++    system("cls");
++
++    repeatChar(39, 'A'); repeatChar(1, ' ');
++    repeatChar(39, 'B'); repeatChar(1, ' ');
++    printf("\n");
++
++    repeatChar(39, 'C'); repeatChar(1, ' ');
++    repeatChar(39, 'D'); repeatChar(1, ' ');
++    printf("\n");
++
++    repeatChar(40, 'E');
++    repeatChar(40, 'F');
++    printf("\n");
++
++    repeatChar(39, 'G'); repeatChar(1, ' ');
++    repeatChar(39, 'H'); repeatChar(1, ' ');
++    printf("\n");
++
++    Sleep(2000);
++
++    setChar(39, 0, '*', 0x24);
++    setChar(39, 1, '*', 0x24);
++
++    setChar(39, 3, ' ', 0x24);
++    setChar(39, 4, ' ', 0x24);
++
++    setChar(38, 6, ' ', 0x24);
++    setChar(38, 7, ' ', 0x24);
++
++    Sleep(2000);
++    setWindowPos(0, 0, 35, 20);
++    setBufferSize(35, 20);
++    trace("DONE");
++
++    printf("Sleeping forever...\n");
++    while(true) { Sleep(1000); }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..50615fc8c792945eac4f0f911af6fe8a98b398ac
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,30 @@@
++#include <windows.h>
++
++#include "TestUtil.cc"
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        startChildProcess(L"CHILD");
++        return 0;
++    }
++
++    const int WIDTH = 25;
++
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(WIDTH, 40);
++    setWindowPos(0, 0, WIDTH, 20);
++
++    system("cls");
++
++    for (int i = 0; i < 100; ++i) {
++        printf("FOO(%d)\n", i);
++    }
++
++    repeatChar(5, '\n');
++    repeatChar(WIDTH * 5, '.');
++    repeatChar(10, '\n');
++    setWindowPos(0, 20, WIDTH, 20);
++    writeBox(0, 5, 1, 10, '|');
++
++    Sleep(120000);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..06fc79f79457ab6be6c3bd87f4f62df8f64cf74d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,26 @@@
++/*
++ * A Win32 program that reads raw console input with ReadFile and echos
++ * it to stdout.
++ */
++
++#include <stdio.h>
++#include <conio.h>
++#include <windows.h>
++
++int main()
++{
++    int count = 0;
++    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
++    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
++    SetConsoleMode(hStdIn, 0);
++
++    while (true) {
++        DWORD actual;
++        char ch;
++        ReadFile(hStdIn, &ch, 1, &actual, NULL);
++        printf("%02x ", ch);
++        if (++count == 50)
++            break;
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b2ea2ad1c5d75eb70b587e0f1f0fbe4922ceb51f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,19 @@@
++/*
++ * A Win32 program that reads raw console input with getch and echos
++ * it to stdout.
++ */
++
++#include <stdio.h>
++#include <conio.h>
++
++int main()
++{
++    int count = 0;
++    while (true) {
++        int ch = getch();
++        printf("%02x ", ch);
++        if (++count == 50)
++            break;
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a40d318a98c2828e8a3ba16a50d9ef30916919e5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,46 @@@
++#define _WIN32_WINNT 0x0501
++#include "../src/shared/DebugClient.cc"
++#include <windows.h>
++#include <stdio.h>
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++
++CALLBACK DWORD writerThread(void*)
++{
++    while (true) {
++        Sleep(1000);
++        trace("writing");
++        printf("X\n");
++        trace("written");
++    }
++}
++
++int main()
++{
++    CreateThread(NULL, 0, writerThread, NULL, 0, NULL);
++    trace("marking console");
++    HWND hwnd = GetConsoleWindow();
++    PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
++
++    Sleep(2000);
++
++    trace("reading output");
++    CHAR_INFO buf[1];
++    COORD bufSize = { 1, 1 };
++    COORD zeroCoord = { 0, 0 };
++    SMALL_RECT readRect = { 0, 0, 0, 0 };
++    ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
++                      buf,
++                      bufSize,
++                      zeroCoord,
++                      &readRect);
++    trace("done reading output");
++
++    Sleep(2000);
++
++    PostMessage(hwnd, WM_CHAR, 27, 0x00010001);
++
++    Sleep(1100);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2777bad456203559c619c4ef7dd9a3c538c288a7
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,70 @@@
++/*
++ * This test demonstrates that putting a console into selection mode does not
++ * block the low-level console APIs, even though it blocks WriteFile.
++ */
++
++#define _WIN32_WINNT 0x0501
++#include "../src/shared/DebugClient.cc"
++#include <windows.h>
++#include <stdio.h>
++
++const int SC_CONSOLE_MARK = 0xFFF2;
++
++CALLBACK DWORD writerThread(void*)
++{
++    CHAR_INFO xChar, fillChar;
++    memset(&xChar, 0, sizeof(xChar));
++    xChar.Char.AsciiChar = 'X';
++    xChar.Attributes = 7;
++    memset(&fillChar, 0, sizeof(fillChar));
++    fillChar.Char.AsciiChar = ' ';
++    fillChar.Attributes = 7;
++    COORD oneCoord = { 1, 1 };
++    COORD zeroCoord = { 0, 0 };
++
++    while (true) {
++        SMALL_RECT writeRegion = { 5, 5, 5, 5 };
++        WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
++                           &xChar, oneCoord,
++                           zeroCoord,
++                           &writeRegion);
++        Sleep(500);
++        SMALL_RECT scrollRect = { 1, 1, 20, 20 };
++        COORD destCoord = { 0, 0 };
++        ScrollConsoleScreenBuffer(GetStdHandle(STD_OUTPUT_HANDLE),
++                                  &scrollRect,
++                                  NULL,
++                                  destCoord,
++                                  &fillChar);
++    }
++}
++
++int main()
++{
++    CreateThread(NULL, 0, writerThread, NULL, 0, NULL);
++    trace("marking console");
++    HWND hwnd = GetConsoleWindow();
++    PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
++
++    Sleep(2000);
++
++    trace("reading output");
++    CHAR_INFO buf[1];
++    COORD bufSize = { 1, 1 };
++    COORD zeroCoord = { 0, 0 };
++    SMALL_RECT readRect = { 0, 0, 0, 0 };
++    ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
++                      buf,
++                      bufSize,
++                      zeroCoord,
++                      &readRect);
++    trace("done reading output");
++
++    Sleep(2000);
++
++    PostMessage(hwnd, WM_CHAR, 27, 0x00010001);
++
++    Sleep(1100);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1fb92aff3df9a585f30a0bcd7d61537b58462f79
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,78 @@@
++/*
++ * Creates a window station and starts a process under it.  The new process
++ * also gets a new console.
++ */
++
++#include <windows.h>
++#include <string.h>
++#include <stdio.h>
++
++int main()
++{
++    BOOL success;
++
++    SECURITY_ATTRIBUTES sa;
++    memset(&sa, 0, sizeof(sa));
++    sa.bInheritHandle = TRUE;
++
++    HWINSTA originalStation = GetProcessWindowStation();
++    printf("originalStation == 0x%x\n", originalStation);
++    HWINSTA station = CreateWindowStation(NULL,
++                                          0,
++                                          WINSTA_ALL_ACCESS,
++                                          &sa);
++    printf("station == 0x%x\n", station);
++    if (!SetProcessWindowStation(station))
++        printf("SetWindowStation failed!\n");
++    HDESK desktop = CreateDesktop("Default", NULL, NULL,
++                                  /*dwFlags=*/0, GENERIC_ALL,
++                                  &sa);
++    printf("desktop = 0x%x\n", desktop);
++
++    char stationName[256];
++    stationName[0] = '\0';
++    success = GetUserObjectInformation(station, UOI_NAME, 
++                                       stationName, sizeof(stationName),
++                                       NULL);
++    printf("stationName = [%s]\n", stationName);
++
++    char startupDesktop[256];
++    sprintf(startupDesktop, "%s\\Default", stationName);
++
++    STARTUPINFO sui;
++    PROCESS_INFORMATION pi;
++    memset(&sui, 0, sizeof(sui));
++    memset(&pi, 0, sizeof(pi));
++    sui.cb = sizeof(STARTUPINFO);
++    sui.lpDesktop = startupDesktop;
++
++    // Start a cmd subprocess, and have it start its own cmd subprocess.
++    // Both subprocesses will connect to the same non-interactive window
++    // station.
++
++    const char program[] = "c:\\windows\\system32\\cmd.exe";
++    char cmdline[256];
++    sprintf(cmdline, "%s /c cmd", program);
++    success = CreateProcess(program,
++                            cmdline,
++                            NULL,
++                            NULL,
++                            /*bInheritHandles=*/FALSE,
++                            /*dwCreationFlags=*/CREATE_NEW_CONSOLE,
++                            NULL, NULL,
++                            &sui,
++                            &pi);
++
++    printf("pid == %d\n", pi.dwProcessId);
++
++    // This sleep is necessary.  We must give the child enough time to
++    // connect to the specified window station.
++    Sleep(5000);
++
++    SetProcessWindowStation(originalStation);
++    CloseWindowStation(station);
++    CloseDesktop(desktop);
++    Sleep(5000);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6e5bf9668228f42c5d340887d0fc524e9f7d868f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,44 @@@
++/* 
++ * A Win32 program that scrolls and writes to the console using the ioctl-like
++ * interface.
++ */
++
++#include <stdio.h>
++#include <windows.h>
++
++int main()
++{
++    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    for (int i = 0; i < 80; ++i) {
++
++        CONSOLE_SCREEN_BUFFER_INFO info;
++        GetConsoleScreenBufferInfo(conout, &info);
++
++        SMALL_RECT src = { 0, 1, info.dwSize.X - 1, info.dwSize.Y - 1 };
++        COORD destOrigin = { 0, 0 };
++        CHAR_INFO fillCharInfo = { 0 };
++        fillCharInfo.Char.AsciiChar = ' ';
++        fillCharInfo.Attributes = 7;
++        ScrollConsoleScreenBuffer(conout,
++                                  &src,
++                                  NULL,
++                                  destOrigin,
++                                  &fillCharInfo);
++
++        CHAR_INFO buffer = { 0 };
++        buffer.Char.AsciiChar = 'X';
++        buffer.Attributes = 7;
++        COORD bufferSize = { 1, 1 };
++        COORD bufferCoord = { 0, 0 };
++        SMALL_RECT writeRegion = { 0, 0, 0, 0 };
++        writeRegion.Left = writeRegion.Right = i;
++        writeRegion.Top = writeRegion.Bottom = 5;
++        WriteConsoleOutput(conout, 
++                           &buffer, bufferSize, bufferCoord,
++                           &writeRegion);
++
++        Sleep(250);
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e6d9558df635a2bcf52d606e9478a689ce142a2a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,27 @@@
++// I noticed this on the ConEmu web site:
++//
++// https://social.msdn.microsoft.com/Forums/en-US/40c8e395-cca9-45c8-b9b8-2fbe6782ac2b/readconsoleoutput-cause-access-violation-writing-location-exception
++// https://conemu.github.io/en/MicrosoftBugs.html
++//
++// In Windows 7, 8, and 8.1, a ReadConsoleOutputW with an out-of-bounds read
++// region crashes the application.  I have reproduced the problem on Windows 8
++// and 8.1, but not on Windows 7.
++//
++
++#include <windows.h>
++
++#include "TestUtil.cc"
++
++int main() {
++    setWindowPos(0, 0, 1, 1);
++    setBufferSize(80, 25);
++    setWindowPos(0, 0, 80, 25);
++
++    const HANDLE conout = openConout();
++    static CHAR_INFO lineBuf[80];
++    SMALL_RECT readRegion = { 0, 999, 79, 999 };
++    const BOOL ret = ReadConsoleOutputW(conout, lineBuf, {80, 1}, {0, 0}, &readRegion);
++    ASSERT(!ret && "ReadConsoleOutputW should have failed");
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a03670ca9290485a7400c6f84536d2af63f4bd25
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,106 @@@
++#include <windows.h>
++
++#include <assert.h>
++#include <stdint.h>
++#include <stdlib.h>
++
++#include <string>
++#include <vector>
++
++static std::wstring mbsToWcs(const std::string &s) {
++    const size_t len = mbstowcs(nullptr, s.c_str(), 0);
++    if (len == static_cast<size_t>(-1)) {
++        assert(false && "mbsToWcs: invalid string");
++    }
++    std::wstring ret;
++    ret.resize(len);
++    const size_t len2 = mbstowcs(&ret[0], s.c_str(), len);
++    assert(len == len2);
++    return ret;
++}
++
++uint32_t parseHex(wchar_t ch, bool &invalid) {
++    if (ch >= L'0' && ch <= L'9') {
++        return ch - L'0';
++    } else if (ch >= L'a' && ch <= L'f') {
++        return ch - L'a' + 10;
++    } else if (ch >= L'A' && ch <= L'F') {
++        return ch - L'A' + 10;
++    } else {
++        invalid = true;
++        return 0;
++    }
++}
++
++int main(int argc, char *argv[]) {
++    std::vector<std::wstring> args;
++    for (int i = 1; i < argc; ++i) {
++        args.push_back(mbsToWcs(argv[i]));
++    }
++
++    std::wstring out;
++    for (const auto &arg : args) {
++        if (!out.empty()) {
++            out.push_back(L' ');
++        }
++        for (size_t i = 0; i < arg.size(); ++i) {
++            wchar_t ch = arg[i];
++            wchar_t nch = i + 1 < arg.size() ? arg[i + 1] : L'\0';
++            if (ch == L'\\') {
++                switch (nch) {
++                    case L'a':  ch = L'\a'; ++i; break;
++                    case L'b':  ch = L'\b'; ++i; break;
++                    case L'e':  ch = L'\x1b'; ++i; break;
++                    case L'f':  ch = L'\f'; ++i; break;
++                    case L'n':  ch = L'\n'; ++i; break;
++                    case L'r':  ch = L'\r'; ++i; break;
++                    case L't':  ch = L'\t'; ++i; break;
++                    case L'v':  ch = L'\v'; ++i; break;
++                    case L'\\': ch = L'\\'; ++i; break;
++                    case L'\'': ch = L'\''; ++i; break;
++                    case L'\"': ch = L'\"'; ++i; break;
++                    case L'\?': ch = L'\?'; ++i; break;
++                    case L'x':
++                        if (i + 3 < arg.size()) {
++                            bool invalid = false;
++                            uint32_t d1 = parseHex(arg[i + 2], invalid);
++                            uint32_t d2 = parseHex(arg[i + 3], invalid);
++                            if (!invalid) {
++                                i += 3;
++                                ch = (d1 << 4) | d2;
++                            }
++                        }
++                        break;
++                    case L'u':
++                        if (i + 5 < arg.size()) {
++                            bool invalid = false;
++                            uint32_t d1 = parseHex(arg[i + 2], invalid);
++                            uint32_t d2 = parseHex(arg[i + 3], invalid);
++                            uint32_t d3 = parseHex(arg[i + 4], invalid);
++                            uint32_t d4 = parseHex(arg[i + 5], invalid);
++                            if (!invalid) {
++                                i += 5;
++                                ch = (d1 << 24) | (d2 << 16) | (d3 << 8) | d4;
++                            }
++                        }
++                        break;
++                    default: break;
++                }
++            }
++            out.push_back(ch);
++        }
++    }
++
++    DWORD actual = 0;
++    if (!WriteConsoleW(
++            GetStdHandle(STD_OUTPUT_HANDLE),
++            out.c_str(),
++            out.size(),
++            &actual,
++            nullptr)) {
++        fprintf(stderr, "WriteConsole failed (is stdout a console?)\n");
++        exit(1);
++    }
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..162993ce337c216f187223773ed6a77fd1702fd3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,9 @@@
++#!/bin/bash
++set -e
++name=$1
++name=${name%.}
++name=${name%.cc}
++name=${name%.exe}
++echo Compiling $name.cc to $name.exe
++i686-w64-mingw32-g++.exe -static -std=c++11 $name.cc -o $name.exe
++i686-w64-mingw32-strip $name.exe
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..675796768473dfb9bae800f70bcfaa95ea1d8547
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,9 @@@
++#!/bin/bash
++set -e
++name=$1
++name=${name%.}
++name=${name%.cc}
++name=${name%.exe}
++echo Compiling $name.cc to $name.exe
++x86_64-w64-mingw32-g++.exe -static -std=c++11 $name.cc -o $name.exe
++x86_64-w64-mingw32-strip $name.exe
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..065c8094e293216919cc7f5f874c2c0b8e632684
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,212 @@@
++#!/bin/bash
++
++FORE=$1
++BACK=$2
++FILL=$3
++
++if [ "$FORE" = "" ]; then
++    FORE=DefaultFore
++fi
++if [ "$BACK" = "" ]; then
++    BACK=DefaultBack
++fi
++
++# To detect color changes, we want a character that fills the whole cell
++# if possible.  U+2588 is perfect, except that it becomes invisible in the
++# original xterm, when bolded.  For that terminal, use something else, like
++# "#" or "@".
++if [ "$FILL" = "" ]; then
++    FILL="█"
++fi
++
++# SGR (Select Graphic Rendition)
++s() {
++    printf '\033[0m'
++    while [ "$1" != "" ]; do
++        printf '\033['"$1"'m'
++        shift
++    done
++}
++
++# Print
++p() {
++    echo -n "$@"
++}
++
++# Print with newline
++pn() {
++    echo "$@"
++}
++
++# For practical reasons, sandwich black and white in-between the other colors.
++FORE_COLORS="31 30 37 32 33 34 35 36"
++BACK_COLORS="41 40 47 42 43 44 45 46"
++
++
++
++### Test order of Invert(7) -- it does not matter what order it appears in.
++
++# The Red color setting here (31) is shadowed by the green setting (32).  The
++# Reverse flag does not cause (32) to alter the background color immediately;
++# instead, the Reverse flag is applied once to determine the final effective
++# Fore/Back colors.
++s 7 31 32; p " -- Should be: $BACK-on-green -- "; s; pn
++s 31 7 32; p " -- Should be: $BACK-on-green -- "; s; pn
++s 31 32 7; p " -- Should be: $BACK-on-green -- "; s; pn
++
++# As above, but for the background color.
++s 7 41 42; p " -- Should be: green-on-$FORE -- "; s; pn
++s 41 7 42; p " -- Should be: green-on-$FORE -- "; s; pn
++s 41 42 7; p " -- Should be: green-on-$FORE -- "; s; pn
++
++# One last, related test
++s 7; p "Invert text"; s 7 1; p " with some words bold"; s; pn;
++s 0; p "Normal text"; s 0 1; p " with some words bold"; s; pn;
++
++pn
++
++
++
++### Test effect of Bold(1) on color, with and without Invert(7).
++
++# The Bold flag does not affect the background color when Reverse is missing.
++# There should always be 8 colored boxes.
++p "  "
++for x in $BACK_COLORS; do
++    s $x; p "-"; s $x 1; p "-"
++done
++s; pn "    Bold should not affect background"
++
++# On some terminals, Bold affects color, and on some it doesn't.  If there
++# are only 8 colored boxes, then the next two tests will also show 8 colored
++# boxes.  If there are 16 boxes, then exactly one of the next two tests will
++# also have 16 boxes.
++p "  "
++for x in $FORE_COLORS; do
++    s $x; p "$FILL"; s $x 1; p "$FILL"
++done
++s; pn "    Does bold affect foreground color?"
++
++# On some terminals, Bold+Invert highlights the final Background color.
++p "  "
++for x in $FORE_COLORS; do
++    s $x 7; p "-"; s $x 7 1; p "-"
++done
++s; pn "    Test if Bold+Invert affects background color"
++
++# On some terminals, Bold+Invert highlights the final Foreground color.
++p "  "
++for x in $BACK_COLORS; do
++    s $x 7; p "$FILL"; s $x 7 1; p "$FILL"
++done
++s; pn "    Test if Bold+Invert affects foreground color"
++
++pn
++
++
++
++### Test for support of ForeHi and BackHi properties.
++
++# ForeHi
++p "  "
++for x in $FORE_COLORS; do
++    hi=$(( $x + 60 ))
++    s $x; p "$FILL"; s $hi; p "$FILL"
++done
++s; pn "    Test for support of ForeHi colors"
++p "  "
++for x in $FORE_COLORS; do
++    hi=$(( $x + 60 ))
++    s $x; p "$FILL"; s $x $hi; p "$FILL"
++done
++s; pn "    Test for support of ForeHi colors (w/compat)"
++
++# BackHi
++p "  "
++for x in $BACK_COLORS; do
++    hi=$(( $x + 60 ))
++    s $x; p "-"; s $hi; p "-"
++done
++s; pn "    Test for support of BackHi colors"
++p "  "
++for x in $BACK_COLORS; do
++    hi=$(( $x + 60 ))
++    s $x; p "-"; s $x $hi; p "-"
++done
++s; pn "    Test for support of BackHi colors (w/compat)"
++
++pn
++
++
++
++### Identify the default fore and back colors.
++
++pn "Match default fore and back colors against 16-color palette"
++pn "  ==fore==  ==back=="
++for fore in $FORE_COLORS; do
++    forehi=$(( $fore + 60 ))
++    back=$(( $fore + 10 ))
++    backhi=$(( $back + 60 ))
++    p "  "
++    s $fore;   p "$FILL"; s; p "$FILL"; s $fore;   p "$FILL"; s; p "  "
++    s $forehi; p "$FILL"; s; p "$FILL"; s $forehi; p "$FILL"; s; p "  "
++    s $back;   p "-"; s; p "-"; s $back;   p "-"; s; p "  "
++    s $backhi; p "-"; s; p "-"; s $backhi; p "-"; s; p "  "
++    pn "  $fore $forehi $back $backhi"
++done
++
++pn
++
++
++
++### Test coloring of rest-of-line.
++
++#
++# When a new line is scrolled in, every cell in the line receives the
++# current background color, which can be the default/transparent color.
++#
++
++p "Newline with red background: usually no red -->"; s 41; pn
++s; pn "This text is plain, but rest is red if scrolled -->"
++s; p " "; s 41; printf '\033[1K'; s; printf '\033[1C'; pn "<-- red Erase-in-Line to beginning"
++s; p "red Erase-in-Line to end -->"; s 41; printf '\033[0K'; s; pn
++pn
++
++
++
++### Moving the cursor around does not change colors of anything.
++
++pn "Test modifying uncolored lines with a colored SGR:"
++pn "aaaa"
++pn
++pn "____e"
++s 31 42; printf '\033[4C\033[3A'; pn "bb"
++pn "cccc"
++pn "dddd"
++s; pn
++
++pn "Test modifying colored+inverted+bold line with plain text:"
++s 42 31 7 1; printf 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\r';
++s; pn "This text is plain and followed by green-on-red -->"
++pn
++
++
++
++### Full-width character overwriting
++
++pn 'Overwrite part of a full-width char with a half-width char'
++p 'initial U+4000 ideographs -->'; s 31 42; p '䀀䀀'; s; pn
++p 'write X to index #1 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[24G'; p X; s; pn
++p 'write X to index #2 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[25G'; p X; s; pn
++p 'write X to index #3 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[26G'; p X; s; pn
++p 'write X to index #4 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[27G'; p X; s; pn
++pn
++
++pn 'Verify that Erase-in-Line can "fix" last char in line'
++p 'original                  -->'; s 31 42; p '䀀䀀'; s; pn
++p 'overwrite                 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[30G'; p 'XXX'; s; pn
++p 'overwrite + Erase-in-Line -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[30G'; p 'XXX'; s; printf '\033[0K'; pn
++p 'original                  -->'; s 31 42; p 'X䀀䀀'; s; pn
++p 'overwrite                 -->'; s 31 42; p 'X䀀䀀'; s 35 44; printf '\033[30G'; p 'ーー'; s; pn
++p 'overwrite + Erase-in-Line -->'; s 31 42; p 'X䀀䀀'; s 35 44; printf '\033[30G'; p 'ーー'; s; printf '\033[0K'; pn
++pn
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d4e36d8e25d53fcd5d29a018bc69e1cb0c5df383
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,300 @@@
++==================================================================
++Notes regarding fonts, code pages, and East Asian character widths
++==================================================================
++
++
++Registry settings
++=================
++
++ * There are console registry settings in `HKCU\Console`.  That key has many
++   default settings (e.g. the default font settings) and also per-app subkeys
++   for app-specific overrides.
++
++ * It is possible to override the code page with an app-specific setting.
++
++ * There are registry settings in
++   `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console`.  In particular,
++   the `TrueTypeFont` subkey has a list of suitable font names associated with
++   various CJK code pages, as well as default font names.
++
++ * There are two values in `HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage`
++   that specify the current code pages -- `OEMCP` and `ACP`.  Setting the
++   system locale via the Control Panel's "Region" or "Language" dialogs seems
++   to change these code page values.
++
++
++Console fonts
++=============
++
++ * The `FontFamily` field of `CONSOLE_FONT_INFOEX` has two parts:
++    - The high four bits can be exactly one of the `FF_xxxx` font families:
++          FF_DONTCARE(0x00)
++          FF_ROMAN(0x10)
++          FF_SWISS(0x20)
++          FF_MODERN(0x30)
++          FF_SCRIPT(0x40)
++          FF_DECORATIVE(0x50)
++    - The low four bits are a bitmask:
++          TMPF_FIXED_PITCH(1) -- actually means variable pitch
++          TMPF_VECTOR(2)
++          TMPF_TRUETYPE(4)
++          TMPF_DEVICE(8)
++
++ * Each console has its own independent console font table.  The current font
++   is identified with an index into this table.  The size of the table is
++   returned by the undocumented `GetNumberOfConsoleFonts` API.  It is apparently
++   possible to get the table size without this API, by instead calling
++   `GetConsoleFontSize` on each nonnegative index starting with 0 until the API
++   fails by returning (0, 0).
++
++ * The font table grows dynamically.  Each time the console is configured with
++   a previously-unused (FaceName, Size) combination, two entries are added to
++   the font table -- one with normal weight and one with bold weight.  Fonts
++   added this way are always TrueType fonts.
++
++ * Initially, the font table appears to contain only raster fonts.  For
++   example, on an English Windows 8 installation, here is the initial font
++   table:
++       font 0: 4x6
++       font 1: 6x8
++       font 2: 8x8
++       font 3: 16x8
++       font 4: 5x12
++       font 5: 7x12
++       font 6: 8x12 -- the current font
++       font 7: 16x12
++       font 8: 12x16
++       font 9: 10x18
++   `GetNumberOfConsoleFonts` returns 10, and this table matches the raster font
++   sizes according to the console properties dialog.
++
++ * With a Japanese or Chinese locale, the initial font table appears to contain
++   the sizes applicable to both the East Asian raster font, as well as the
++   sizes for the CP437/CP1252 raster font.
++
++ * The index passed to `SetCurrentConsoleFontEx` apparently has no effect.
++   The undocumented `SetConsoleFont` API, however, accepts *only* a font index,
++   and on Windows 8 English, it switches between all 10 fonts, even font index
++   #0.
++
++ * If the index passed to `SetConsoleFont` identifies a Raster Font
++   incompatible with the current code page, then another Raster Font is
++   activated.
++
++ * Passing "Terminal" to `SetCurrentConsoleFontEx` seems to have no effect.
++   Perhaps relatedly, `SetCurrentConsoleFontEx` does not fail if it is given a
++   bogus `FaceName`.  Some font is still chosen and activated.  Passing a face
++   name and height seems to work reliably, modulo the CP936 issue described
++   below.
++
++
++Console fonts and code pages
++============================
++
++ * On an English Windows installation, the default code page is 437, and it
++   cannot be set to 932 (Shift-JIS).  (The API call fails.)  Changing the
++   system locale to "Japanese (Japan)" using the Region/Language dialog
++   changes the default CP to 932 and permits changing the console CP between
++   437 and 932.
++
++ * A console has both an input code page and an output code page
++   (`{Get,Set}ConsoleCP` and `{Get,Set}ConsoleOutputCP`).  I'm not going to
++   distinguish between the two for this document; presumably only the output
++   CP matters.  The code page can change while the console is open, e.g.
++   by running `mode con: cp select={932,437,1252}` or by calling
++   `SetConsoleOutputCP`.
++
++ * The current code page restricts which TrueType fonts and which Raster Font
++   sizes are available in the console properties dialog.  This can change
++   while the console is open.
++
++ * Changing the code page almost(?) always changes the current console font.
++   So far, I don't know how the new font is chosen.
++
++ * With a CP of 932, the only TrueType font available in the console properties
++   dialog is "MS Gothic", displayed as "MS ゴシック".  It is still possible to
++   use the English-default TrueType console fonts, Lucida Console and Consolas,
++   via `SetCurrentConsoleFontEx`.
++
++ * When using a Raster Font and CP437 or CP1252, writing a UTF-16 codepoint not
++   representable in the code page instead writes a question mark ('?') to the
++   console.  This conversion does not apply with a TrueType font, nor with the
++   Raster Font for CP932 or CP936.
++
++
++ReadConsoleOutput and double-width characters
++==============================================
++
++ * With a Raster Font active, when `ReadConsoleOutputW` reads two cells of a
++   double-width character, it fills only a single `CHAR_INFO` structure.  The
++   unused trailing `CHAR_INFO` structures are zero-filled.  With a TrueType
++   font active, `ReadConsoleOutputW` instead fills two `CHAR_INFO` structures,
++   the first marked with `COMMON_LVB_LEADING_BYTE` and the second marked with
++   `COMMON_LVB_TRAILING_BYTE`.  The flag is a misnomer--there aren't two
++   *bytes*, but two cells, and they have equal `CHAR_INFO.Char.UnicodeChar`
++   values.
++
++ * `ReadConsoleOutputA`, on the other hand, reads two `CHAR_INFO` cells, and
++   if the UTF-16 value can be represented as two bytes in the ANSI/OEM CP, then
++   the two bytes are placed in the two `CHAR_INFO.Char.AsciiChar` values, and
++   the `COMMON_LVB_{LEADING,TRAILING}_BYTE` values are also used.  If the
++   codepoint isn't representable, I don't remember what happens -- I think the
++   `AsciiChar` values take on an invalid marker.
++
++ * Reading only one cell of a double-width character reads a space (U+0020)
++   instead.  Raster-vs-TrueType and wide-vs-ANSI do not matter.
++    - XXX: what about attributes?  Can a double-width character have mismatched
++      color attributes?
++    - XXX: what happens when writing to just one cell of a double-width
++      character?
++
++
++Default Windows fonts for East Asian languages
++==============================================
++CP932 / Japanese: "MS ゴシック" (MS Gothic)
++CP936 / Chinese Simplified: "新宋体" (SimSun)
++
++
++Unreliable character width (half-width vs full-width)
++=====================================================
++
++The half-width vs full-width status of a codepoint depends on at least these variables:
++ * OS version (Win10 legacy and new modes are different versions)
++ * system locale (English vs Japanese vs Chinese Simplified vs Chinese Traditional, etc)
++ * code page (437 vs 932 vs 936, etc)
++ * raster vs TrueType (Terminal vs MS Gothic vs SimSun, etc)
++ * font size
++ * rendered-vs-model (rendered width can be larger or smaller than model width)
++
++Example 1: U+2014 (EM DASH): East_Asian_Width: Ambiguous
++--------------------------------------------------------
++                                            rendered        modeled
++CP932: Win7/8 Raster Fonts                  half            half
++CP932: Win7/8 Gothic 14/15px                half            full
++CP932: Win7/8 Consolas 14/15px              half            full
++CP932: Win7/8 Lucida Console 14px           half            full
++CP932: Win7/8 Lucida Console 15px           half            half
++CP932: Win10New Raster Fonts                half            half
++CP932: Win10New Gothic 14/15px              half            half
++CP932: Win10New Consolas 14/15px            half            half
++CP932: Win10New Lucida Console 14/15px      half            half
++
++CP936: Win7/8 Raster Fonts                  full            full
++CP936: Win7/8 SimSun 14px                   full            full
++CP936: Win7/8 SimSun 15px                   full            half
++CP936: Win7/8 Consolas 14/15px              half            full
++CP936: Win10New Raster Fonts                full            full
++CP936: Win10New SimSum 14/15px              full            full
++CP936: Win10New Consolas 14/15px            half            half
++
++Example 2: U+3044 (HIRAGANA LETTER I): East_Asian_Width: Wide
++-------------------------------------------------------------
++                                            rendered        modeled
++CP932: Win7/8/10N Raster Fonts              full            full
++CP932: Win7/8/10N Gothic 14/15px            full            full
++CP932: Win7/8/10N Consolas 14/15px          half(*2)        full
++CP932: Win7/8/10N Lucida Console 14/15px    half(*3)        full
++
++CP936: Win7/8/10N Raster Fonts              full            full
++CP936: Win7/8/10N SimSun 14/15px            full            full
++CP936: Win7/8/10N Consolas 14/15px          full            full
++
++Example 3: U+30FC (KATAKANA-HIRAGANA PROLONGED SOUND MARK): East_Asian_Width: Wide
++----------------------------------------------------------------------------------
++                                            rendered        modeled
++CP932: Win7 Raster Fonts                    full            full
++CP932: Win7 Gothic 14/15px                  full            full
++CP932: Win7 Consolas 14/15px                half(*2)        full
++CP932: Win7 Lucida Console 14px             half(*3)        full
++CP932: Win7 Lucida Console 15px             half(*3)        half
++CP932: Win8 Raster Fonts                    full            full
++CP932: Win8 Gothic 14px                     full            half
++CP932: Win8 Gothic 15px                     full            full
++CP932: Win8 Consolas 14/15px                half(*2)        full
++CP932: Win8 Lucida Console 14px             half(*3)        full
++CP932: Win8 Lucida Console 15px             half(*3)        half
++CP932: Win10New Raster Fonts                full            full
++CP932: Win10New Gothic 14/15px              full            full
++CP932: Win10New Consolas 14/15px            half(*2)        half
++CP932: Win10New Lucida Console 14/15px      half(*2)        half
++
++CP936: Win7/8 Raster Fonts                  full            full
++CP936: Win7/8 SimSun 14px                   full            full
++CP936: Win7/8 SimSun 15px                   full            half
++CP936: Win7/8 Consolas 14px                 full            full
++CP936: Win7/8 Consolas 15px                 full            half
++CP936: Win10New Raster Fonts                full            full
++CP936: Win10New SimSum 14/15px              full            full
++CP936: Win10New Consolas 14/15px            full            full
++
++Example 4: U+4000 (CJK UNIFIED IDEOGRAPH-4000): East_Asian_Width: Wide
++----------------------------------------------------------------------
++                                            rendered        modeled
++CP932: Win7 Raster Fonts                    half(*1)        half
++CP932: Win7 Gothic 14/15px                  full            full
++CP932: Win7 Consolas 14/15px                half(*2)        full
++CP932: Win7 Lucida Console 14px             half(*3)        full
++CP932: Win7 Lucida Console 15px             half(*3)        half
++CP932: Win8 Raster Fonts                    half(*1)        half
++CP932: Win8 Gothic 14px                     full            half
++CP932: Win8 Gothic 15px                     full            full
++CP932: Win8 Consolas 14/15px                half(*2)        full
++CP932: Win8 Lucida Console 14px             half(*3)        full
++CP932: Win8 Lucida Console 15px             half(*3)        half
++CP932: Win10New Raster Fonts                half(*1)        half
++CP932: Win10New Gothic 14/15px              full            full
++CP932: Win10New Consolas 14/15px            half(*2)        half
++CP932: Win10New Lucida Console 14/15px      half(*2)        half
++
++CP936: Win7/8 Raster Fonts                  full            full
++CP936: Win7/8 SimSun 14px                   full            full
++CP936: Win7/8 SimSun 15px                   full            half
++CP936: Win7/8 Consolas 14px                 full            full
++CP936: Win7/8 Consolas 15px                 full            half
++CP936: Win10New Raster Fonts                full            full
++CP936: Win10New SimSum 14/15px              full            full
++CP936: Win10New Consolas 14/15px            full            full
++
++(*1) Rendered as a half-width filled white box
++(*2) Rendered as a half-width box with a question mark inside
++(*3) Rendered as a half-width empty box
++(!!) One of the only places in Win10New where rendered and modeled width disagree
++
++
++Windows quirk: unreliable font heights with CP936 / Chinese Simplified
++======================================================================
++
++When I set the font to 新宋体 17px, using either the properties dialog or
++`SetCurrentConsoleFontEx`, the height reported by `GetCurrentConsoleFontEx` is
++not 17, but is instead 19.  The same problem does not affect Raster Fonts,
++nor have I seen the problem in the English or Japanese locales.  I observed
++this with Windows 7 and Windows 10 new mode.
++
++If I set the font using the facename, width, *and* height, then the
++`SetCurrentConsoleFontEx` and `GetCurrentConsoleFontEx` values agree.  If I
++set the font using *only* the facename and height, then the two values
++disagree.
++
++
++Windows bug: GetCurrentConsoleFontEx is initially invalid
++=========================================================
++
++ - Assume there is no configured console font name in the registry.  In this
++   case, the console defaults to a raster font.
++ - Open a new console and call the `GetCurrentConsoleFontEx` API.
++ - The `FaceName` field of the returned `CONSOLE_FONT_INFOEX` data
++   structure is incorrect.  On Windows 7, 8, and 10, I observed that the
++   field was blank.  On Windows 8, occasionally, it instead contained:
++      U+AE72 U+75BE U+0001
++   The other fields of the structure all appeared correct:
++      nFont=6 dwFontSize=(8,12) FontFamily=0x30 FontWeight=400
++ - The `FaceName` field becomes initialized easily:
++    - Open the console properties dialog and click OK.  (Cancel is not
++      sufficient.)
++    - Call the undocumented `SetConsoleFont` with the current font table
++      index, which is 6 in the example above.
++ - It seems that the console uncritically accepts whatever string is
++   stored in the registry, including a blank string, and passes it on the
++   the `GetCurrentConsoleFontEx` caller.  It is possible to get the console
++   to *write* a blank setting into the registry -- simply open the console
++   (default or app-specific) properties and click OK.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0e98d648c54cc806859ec2322e476f2272e16c25
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,201 @@@
++/*
++
++Test program demonstrating a problem in Windows 15048's ReadConsoleOutput API.
++
++To compile:
++
++    cl /nologo /EHsc winbug-15048.cc shell32.lib
++
++Example of regressed input:
++
++Case 1:
++
++    > chcp 932
++    > winbug-15048 -face-gothic 3044
++
++    Correct output:
++
++        1**34      (nb: U+3044 replaced with '**' to avoid MSVC encoding warning)
++        5678
++
++        ReadConsoleOutputW (both rows, 3 cols)
++        row 0: U+0031(0007) U+3044(0107) U+3044(0207) U+0033(0007)
++        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007)
++
++        ReadConsoleOutputW (both rows, 4 cols)
++        row 0: U+0031(0007) U+3044(0107) U+3044(0207) U+0033(0007) U+0034(0007)
++        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007)
++
++        ReadConsoleOutputW (second row)
++        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007)
++
++        ...
++
++    Win10 15048 bad output:
++
++        1**34
++        5678
++
++        ReadConsoleOutputW (both rows, 3 cols)
++        row 0: U+0031(0007) U+3044(0007) U+0033(0007) U+0035(0007)
++        row 1: U+0036(0007) U+0037(0007) U+0038(0007) U+0000(0000)
++
++        ReadConsoleOutputW (both rows, 4 cols)
++        row 0: U+0031(0007) U+3044(0007) U+0033(0007) U+0034(0007) U+0035(0007)
++        row 1: U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007) U+0000(0000)
++
++        ReadConsoleOutputW (second row)
++        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007)
++
++        ...
++
++    The U+3044 character (HIRAGANA LETTER I) occupies two columns, but it only
++    fills one record in the ReadConsoleOutput output buffer, which has the
++    effect of shifting the first cell of the second row into the last cell of
++    the first row.  Ordinarily, the first and second cells would also have the
++    COMMON_LVB_LEADING_BYTE and COMMON_LVB_TRAILING_BYTE attributes set, which
++    allows winpty to detect the double-column character.
++
++Case 2:
++
++    > chcp 437
++    > winbug-15048 -face "Lucida Console" -h 4 221A
++
++    The same issue happens with U+221A (SQUARE ROOT), but only in certain
++    fonts.  The console seems to think this character occupies two columns
++    if the font is sufficiently small.  The Windows console properties dialog
++    doesn't allow fonts below 5 pt, but winpty tries to use 2pt and 4pt Lucida
++    Console to allow very large console windows.
++
++Case 3:
++
++    > chcp 437
++    > winbug-15048 -face "Lucida Console" -h 12 FF12
++
++    The console selection system thinks U+FF12 (FULLWIDTH DIGIT TWO) occupies
++    two columns, which happens to be correct, but it's displayed as a single
++    column unrecognized character.  It otherwise behaves the same as the other
++    cases.
++
++*/
++
++#include <windows.h>
++#include <assert.h>
++#include <string.h>
++#include <stdlib.h>
++#include <stdio.h>
++#include <wchar.h>
++
++#include <string>
++
++#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0]))
++
++// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
++const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // Japanese
++const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // Simplified Chinese
++const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // Traditional Chinese
++const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // Korean
++
++static void set_font(const wchar_t *name, int size) {
++    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++    CONSOLE_FONT_INFOEX fontex {};
++    fontex.cbSize = sizeof(fontex);
++    fontex.dwFontSize.Y = size;
++    fontex.FontWeight = 400;
++    fontex.FontFamily = 0x36;
++    wcsncpy(fontex.FaceName, name, COUNT_OF(fontex.FaceName));
++    assert(SetCurrentConsoleFontEx(conout, FALSE, &fontex));
++}
++
++static void usage(const wchar_t *prog) {
++    printf("Usage: %ls [options]\n", prog);
++    printf("  -h HEIGHT\n");
++    printf("  -face FACENAME\n");
++    printf("  -face-{gothic|simsun|minglight|gulimche) [JP,CN-sim,CN-tra,KR]\n");
++    printf("  hhhh -- print U+hhhh\n");
++    exit(1);
++}
++
++static void dump_region(SMALL_RECT region, const char *name) {
++    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    CHAR_INFO buf[1000];
++    memset(buf, 0xcc, sizeof(buf));
++
++    const int w = region.Right - region.Left + 1;
++    const int h = region.Bottom - region.Top + 1;
++
++    assert(ReadConsoleOutputW(
++        conout, buf, { (short)w, (short)h }, { 0, 0 },
++        &region));
++
++    printf("\n");
++    printf("ReadConsoleOutputW (%s)\n", name);
++    for (int y = 0; y < h; ++y) {
++        printf("row %d: ", region.Top + y);
++        for (int i = 0; i < region.Left * 13; ++i) {
++            printf(" ");
++        }
++        for (int x = 0; x < w; ++x) {
++            const int i = y * w + x;
++            printf("U+%04x(%04x) ", buf[i].Char.UnicodeChar, buf[i].Attributes);
++        }
++        printf("\n");
++    }
++}
++
++int main() {
++    wchar_t *cmdline = GetCommandLineW();
++    int argc = 0;
++    wchar_t **argv = CommandLineToArgvW(cmdline, &argc);
++    const wchar_t *font_name = L"Lucida Console";
++    int font_height = 8;
++    int test_ch = 0xff12; // U+FF12 FULLWIDTH DIGIT TWO
++
++    for (int i = 1; i < argc; ++i) {
++        const std::wstring arg = argv[i];
++        const std::wstring next = i + 1 < argc ? argv[i + 1] : L"";
++        if (arg == L"-face" && i + 1 < argc) {
++            font_name = argv[i + 1];
++            i++;
++        } else if (arg == L"-face-gothic") {
++            font_name = kMSGothic;
++        } else if (arg == L"-face-simsun") {
++            font_name = kNSimSun;
++        } else if (arg == L"-face-minglight") {
++            font_name = kMingLight;
++        } else if (arg == L"-face-gulimche") {
++            font_name = kGulimChe;
++        } else if (arg == L"-h" && i + 1 < argc) {
++            font_height = _wtoi(next.c_str());
++            i++;
++        } else if (arg.c_str()[0] != '-') {
++            test_ch = wcstol(arg.c_str(), NULL, 16);
++        } else {
++            printf("Unrecognized argument: %ls\n", arg.c_str());
++            usage(argv[0]);
++        }
++    }
++
++    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
++
++    set_font(font_name, font_height);
++
++    system("cls");
++    DWORD actual = 0;
++    wchar_t output[] = L"1234\n5678\n";
++    output[1] = test_ch;
++    WriteConsoleW(conout, output, 10, &actual, nullptr);
++
++    dump_region({ 0, 0, 3, 1 }, "both rows, 3 cols");
++    dump_region({ 0, 0, 4, 1 }, "both rows, 4 cols");
++    dump_region({ 0, 1, 4, 1 }, "second row");
++    dump_region({ 0, 0, 4, 0 }, "first row");
++    dump_region({ 1, 0, 4, 0 }, "first row, skip 1");
++    dump_region({ 2, 0, 4, 0 }, "first row, skip 2");
++    dump_region({ 3, 0, 4, 0 }, "first row, skip 3");
++
++    set_font(font_name, 14);
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b6bca7b07936596a75c73a775cd9aa35de5b6ab3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,36 @@@
++@echo off
++
++setlocal
++cd %~dp0..
++set Path=C:\Python27;C:\Program Files\Git\cmd;%Path%
++
++call "%VS140COMNTOOLS%\VsDevCmd.bat" || goto :fail
++
++rmdir /s/q build-libpty 2>NUL
++mkdir build-libpty\win
++mkdir build-libpty\win\x86
++mkdir build-libpty\win\x86_64
++mkdir build-libpty\win\xp
++
++rmdir /s/q src\Release  2>NUL
++rmdir /s/q src\.vs      2>NUL
++del src\*.vcxproj src\*.vcxproj.filters src\*.sln src\*.sdf 2>NUL
++
++call vcbuild.bat --msvc-platform Win32 --gyp-msvs-version 2015 --toolset v140_xp || goto :fail
++copy src\Release\Win32\winpty.dll           build-libpty\win\xp || goto :fail
++copy src\Release\Win32\winpty-agent.exe     build-libpty\win\xp || goto :fail
++
++call vcbuild.bat --msvc-platform Win32 --gyp-msvs-version 2015 || goto :fail
++copy src\Release\Win32\winpty.dll           build-libpty\win\x86 || goto :fail
++copy src\Release\Win32\winpty-agent.exe     build-libpty\win\x86 || goto :fail
++
++call vcbuild.bat --msvc-platform x64 --gyp-msvs-version 2015 || goto :fail
++copy src\Release\x64\winpty.dll             build-libpty\win\x86_64 || goto :fail
++copy src\Release\x64\winpty-agent.exe       build-libpty\win\x86_64 || goto :fail
++
++echo success
++goto :EOF
++
++:fail
++echo error: build failed
++exit /b 1
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b46cd5b8f42149d352a092abe271fc179eca4766
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,53 @@@
++import os
++import sys
++
++if os.name != "nt":
++    sys.exit("Error: ship scripts require native Python 2.7. (wrong os.name)")
++if sys.version_info[0:2] != (2,7):
++    sys.exit("Error: ship scripts require native Python 2.7. (wrong version)")
++
++import glob
++import shutil
++import subprocess
++from distutils.spawn import find_executable
++
++topDir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
++
++with open(topDir + "/VERSION.txt", "rt") as f:
++    winptyVersion = f.read().strip()
++
++def rmrf(patterns):
++    for pattern in patterns:
++        for path in glob.glob(pattern):
++            if os.path.isdir(path) and not os.path.islink(path):
++                print "+ rm -r " + path
++                sys.stdout.flush()
++                shutil.rmtree(path)
++            elif os.path.isfile(path):
++                print "+ rm " + path
++                sys.stdout.flush()
++                os.remove(path)
++
++def mkdir(path):
++    if not os.path.isdir(path):
++        os.makedirs(path)
++
++def requireExe(name, guesses):
++    if find_executable(name) is None:
++        for guess in guesses:
++            if os.path.exists(guess):
++                newDir = os.path.dirname(guess)
++                print "Adding " + newDir + " to Path to provide " + name
++                os.environ["Path"] = newDir + ";" + os.environ["Path"]
++    ret = find_executable(name)
++    if ret is None:
++        sys.exit("Error: required EXE is missing from Path: " + name)
++    return ret
++
++requireExe("git.exe", [
++    "C:\\Program Files\\Git\\cmd\\git.exe",
++    "C:\\Program Files (x86)\\Git\\cmd\\git.exe"
++])
++
++commitHash = subprocess.check_output(["git.exe", "rev-parse", "HEAD"]).decode().strip()
++defaultPathEnviron = "C:\\Windows\\System32;C:\\Windows"
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..220f02b2780b344f3fe370abe73aa01f05210457
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,165 @@@
++#!python
++
++# Copyright (c) 2016 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++#
++# Run with native CPython 2.7.
++#
++# This script looks for MSVC using a version-specific environment variable,
++# such as VS140COMNTOOLS for MSVC 2015.
++#
++
++import common_ship
++
++import argparse
++import os
++import shutil
++import subprocess
++import sys
++
++os.chdir(common_ship.topDir)
++ZIP_TOOL = common_ship.requireExe("7z.exe", [
++    "C:\\Program Files\\7-Zip\\7z.exe",
++    "C:\\Program Files (x86)\\7-Zip\\7z.exe",
++])
++
++MSVC_VERSION_TABLE = {
++    "2015" : {
++        "package_name" : "msvc2015",
++        "gyp_version" : "2015",
++        "common_tools_env" : "VS140COMNTOOLS",
++        "xp_toolset" : "v140_xp",
++    },
++    "2013" : {
++        "package_name" : "msvc2013",
++        "gyp_version" : "2013",
++        "common_tools_env" : "VS120COMNTOOLS",
++        "xp_toolset" : "v120_xp",
++    },
++}
++
++ARCH_TABLE = {
++    "x64" : {
++        "msvc_platform" : "x64",
++    },
++    "ia32" : {
++        "msvc_platform" : "Win32",
++    },
++}
++
++def readArguments():
++    parser = argparse.ArgumentParser()
++    parser.add_argument("--msvc-version", default="2015")
++    ret = parser.parse_args()
++    if ret.msvc_version not in MSVC_VERSION_TABLE:
++        sys.exit("Error: unrecognized version: " + ret.msvc_version + ". " +
++            "Versions: " + " ".join(sorted(MSVC_VERSION_TABLE.keys())))
++    return ret
++
++ARGS = readArguments()
++
++def checkoutGyp():
++    if os.path.isdir("build-gyp"):
++        return
++    subprocess.check_call([
++        "git.exe",
++        "clone",
++        "https://chromium.googlesource.com/external/gyp",
++        "build-gyp"
++    ])
++
++def cleanMsvc():
++    common_ship.rmrf("""
++        src/Release src/.vs src/gen
++        src/*.vcxproj src/*.vcxproj.filters src/*.sln src/*.sdf
++    """.split())
++
++def build(arch, packageDir, xp=False):
++    archInfo = ARCH_TABLE[arch]
++    versionInfo = MSVC_VERSION_TABLE[ARGS.msvc_version]
++
++    devCmdPath = os.path.join(os.environ[versionInfo["common_tools_env"]], "VsDevCmd.bat")
++    if not os.path.isfile(devCmdPath):
++        sys.exit("Error: MSVC environment script missing: " + devCmdPath)
++
++    newEnv = os.environ.copy()
++    newEnv["PATH"] = os.path.dirname(sys.executable) + ";" + common_ship.defaultPathEnviron
++    commandLine = (
++        '"' + devCmdPath + '" && '
++        " vcbuild.bat" +
++        " --gyp-msvs-version " + versionInfo["gyp_version"] +
++        " --msvc-platform " + archInfo["msvc_platform"] +
++        " --commit-hash " + common_ship.commitHash
++    )
++
++    subprocess.check_call(commandLine, shell=True, env=newEnv)
++
++    archPackageDir = os.path.join(packageDir, arch)
++    if xp:
++        archPackageDir += "_xp"
++
++    common_ship.mkdir(archPackageDir + "/bin")
++    common_ship.mkdir(archPackageDir + "/lib")
++
++    binSrc = os.path.join(common_ship.topDir, "src/Release", archInfo["msvc_platform"])
++
++    shutil.copy(binSrc + "/winpty.dll",                 archPackageDir + "/bin")
++    shutil.copy(binSrc + "/winpty-agent.exe",           archPackageDir + "/bin")
++    shutil.copy(binSrc + "/winpty-debugserver.exe",     archPackageDir + "/bin")
++    shutil.copy(binSrc + "/winpty.lib",                 archPackageDir + "/lib")
++
++def buildPackage():
++    versionInfo = MSVC_VERSION_TABLE[ARGS.msvc_version]
++
++    packageName = "winpty-%s-%s" % (
++        common_ship.winptyVersion,
++        versionInfo["package_name"],
++    )
++
++    packageRoot = os.path.join(common_ship.topDir, "ship/packages")
++    packageDir = os.path.join(packageRoot, packageName)
++    packageFile = packageDir + ".zip"
++
++    common_ship.rmrf([packageDir])
++    common_ship.rmrf([packageFile])
++    common_ship.mkdir(packageDir)
++
++    checkoutGyp()
++    cleanMsvc()
++    build("ia32", packageDir, True)
++    build("x64", packageDir, True)
++    cleanMsvc()
++    build("ia32", packageDir)
++    build("x64", packageDir)
++
++    topDir = common_ship.topDir
++
++    common_ship.mkdir(packageDir + "/include")
++    shutil.copy(topDir + "/src/include/winpty.h",               packageDir + "/include")
++    shutil.copy(topDir + "/src/include/winpty_constants.h",     packageDir + "/include")
++    shutil.copy(topDir + "/LICENSE",                            packageDir)
++    shutil.copy(topDir + "/README.md",                          packageDir)
++    shutil.copy(topDir + "/RELEASES.md",                        packageDir)
++
++    subprocess.check_call([ZIP_TOOL, "a", packageFile, "."], cwd=packageDir)
++
++if __name__ == "__main__":
++    buildPackage()
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..12874bac74fecc6349e68b8d5012314e0d5b7195
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,108 @@@
++#!python
++
++# Copyright (c) 2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++#
++# Run with native CPython 2.7 on a 64-bit computer.
++#
++# Each of the targets in BUILD_TARGETS must be installed to the default
++# location.  Each target must have the appropriate MinGW and non-MinGW
++# compilers installed, as well as make and tar.
++#
++
++import common_ship
++
++import multiprocessing
++import os
++import shutil
++import subprocess
++import sys
++
++os.chdir(common_ship.topDir)
++
++def dllVersion(path):
++    version = subprocess.check_output(
++        ["powershell.exe",
++        "[System.Diagnostics.FileVersionInfo]::GetVersionInfo(\"" + path + "\").FileVersion"])
++    return version.strip()
++
++# Determine other build parameters.
++print "Determining Cygwin/MSYS2 DLL versions..."
++sys.stdout.flush()
++BUILD_TARGETS = [
++    # {
++    #     "name": "msys",
++    #     "path": "C:\\MinGW\\bin;C:\\MinGW\\msys\\1.0\\bin",
++    #     # The parallel make.exe in the original MSYS/MinGW project hangs.
++    #     "make_binary": "mingw32-make.exe",
++    # },
++    {
++        "name": "msys2-" + dllVersion("C:\\msys32\\usr\\bin\\msys-2.0.dll") + "-ia32",
++        "path": "C:\\msys32\\mingw32\\bin;C:\\msys32\\usr\\bin",
++    },
++    {
++        "name": "msys2-" + dllVersion("C:\\msys64\\usr\\bin\\msys-2.0.dll") + "-x64",
++        "path": "C:\\msys64\\mingw64\\bin;C:\\msys64\\usr\\bin",
++    },
++    {
++        "name": "cygwin-" + dllVersion("C:\\cygwin\\bin\\cygwin1.dll") + "-ia32",
++        "path": "C:\\cygwin\\bin",
++    },
++    {
++        "name": "cygwin-" + dllVersion("C:\\cygwin64\\bin\\cygwin1.dll") + "-x64",
++        "path": "C:\\cygwin64\\bin",
++    },
++]
++
++def buildTarget(target):
++    packageName = "winpty-" + common_ship.winptyVersion + "-" + target["name"]
++    if os.path.exists("ship\\packages\\" + packageName):
++        shutil.rmtree("ship\\packages\\" + packageName)
++    oldPath = os.environ["PATH"]
++    os.environ["PATH"] = target["path"] + ";" + common_ship.defaultPathEnviron
++    subprocess.check_call(["sh.exe", "configure"])
++    makeBinary = target.get("make_binary", "make.exe")
++    subprocess.check_call([makeBinary, "clean"])
++    makeBaseCmd = [
++        makeBinary,
++        "USE_PCH=0",
++        "COMMIT_HASH=" + common_ship.commitHash,
++        "PREFIX=ship/packages/" + packageName
++    ]
++    subprocess.check_call(makeBaseCmd + ["all", "tests", "-j%d" % multiprocessing.cpu_count()])
++    subprocess.check_call(["build\\trivial_test.exe"])
++    subprocess.check_call(makeBaseCmd + ["install"])
++    subprocess.check_call(["tar.exe", "cvfz",
++        packageName + ".tar.gz",
++        packageName], cwd=os.path.join(os.getcwd(), "ship", "packages"))
++    os.environ["PATH"] = oldPath
++
++def main():
++    oldPath = os.environ["PATH"]
++    for t in BUILD_TARGETS:
++        os.environ["PATH"] = t["path"] + ";" + common_ship.defaultPathEnviron
++        subprocess.check_output(["tar.exe", "--help"])
++        subprocess.check_output(["make.exe", "--help"])
++    for t in BUILD_TARGETS:
++        buildTarget(t)
++
++if __name__ == "__main__":
++    main()
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a77b6442c6d98a9ad45509c0b95aa2b70e46551a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,605 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Agent.h"
++
++#include <windows.h>
++
++#include <stdint.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include <string>
++#include <utility>
++#include <vector>
++
++#include "../include/winpty_constants.h"
++
++#include "../shared/AgentMsg.h"
++#include "../shared/Buffer.h"
++#include "../shared/DebugClient.h"
++#include "../shared/GenRandom.h"
++#include "../shared/StringBuilder.h"
++#include "../shared/StringUtil.h"
++#include "../shared/WindowsVersion.h"
++#include "../shared/WinptyAssert.h"
++
++#include "ConsoleFont.h"
++#include "ConsoleInput.h"
++#include "NamedPipe.h"
++#include "Scraper.h"
++#include "Terminal.h"
++#include "Win32ConsoleBuffer.h"
++
++namespace {
++
++static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
++{
++    if (dwCtrlType == CTRL_C_EVENT) {
++        // Do nothing and claim to have handled the event.
++        return TRUE;
++    }
++    return FALSE;
++}
++
++// We can detect the new Windows 10 console by observing the effect of the
++// Mark command.  In older consoles, Mark temporarily moves the cursor to the
++// top-left of the console window.  In the new console, the cursor isn't
++// initially moved.
++//
++// We might like to use Mark to freeze the console, but we can't, because when
++// the Mark command ends, the console moves the cursor back to its starting
++// point, even if the console application has moved it in the meantime.
++static void detectNewWindows10Console(
++        Win32Console &console, Win32ConsoleBuffer &buffer)
++{
++    if (!isAtLeastWindows8()) {
++        return;
++    }
++
++    ConsoleScreenBufferInfo info = buffer.bufferInfo();
++
++    // Make sure the window isn't 1x1.  AFAIK, this should never happen
++    // accidentally.  It is difficult to make it happen deliberately.
++    if (info.srWindow.Left == info.srWindow.Right &&
++            info.srWindow.Top == info.srWindow.Bottom) {
++        trace("detectNewWindows10Console: Initial console window was 1x1 -- "
++              "expanding for test");
++        setSmallFont(buffer.conout(), 400, false);
++        buffer.moveWindow(SmallRect(0, 0, 1, 1));
++        buffer.resizeBuffer(Coord(400, 1));
++        buffer.moveWindow(SmallRect(0, 0, 2, 1));
++        // This use of GetLargestConsoleWindowSize ought to be unnecessary
++        // given the behavior I've seen from moveWindow(0, 0, 1, 1), but
++        // I'd like to be especially sure, considering that this code will
++        // rarely be tested.
++        const auto largest = GetLargestConsoleWindowSize(buffer.conout());
++        buffer.moveWindow(
++            SmallRect(0, 0, std::min(largest.X, buffer.bufferSize().X), 1));
++        info = buffer.bufferInfo();
++        ASSERT(info.srWindow.Right > info.srWindow.Left &&
++            "Could not expand console window from 1x1");
++    }
++
++    // Test whether MARK moves the cursor.
++    const Coord initialPosition(info.srWindow.Right, info.srWindow.Bottom);
++    buffer.setCursorPosition(initialPosition);
++    ASSERT(!console.frozen());
++    console.setFreezeUsesMark(true);
++    console.setFrozen(true);
++    const bool isNewW10 = (buffer.cursorPosition() == initialPosition);
++    console.setFrozen(false);
++    buffer.setCursorPosition(Coord(0, 0));
++
++    trace("Attempting to detect new Windows 10 console using MARK: %s",
++        isNewW10 ? "detected" : "not detected");
++    console.setFreezeUsesMark(false);
++    console.setNewW10(isNewW10);
++}
++
++static inline WriteBuffer newPacket() {
++    WriteBuffer packet;
++    packet.putRawValue<uint64_t>(0); // Reserve space for size.
++    return packet;
++}
++
++static HANDLE duplicateHandle(HANDLE h) {
++    HANDLE ret = nullptr;
++    if (!DuplicateHandle(
++            GetCurrentProcess(), h,
++            GetCurrentProcess(), &ret,
++            0, FALSE, DUPLICATE_SAME_ACCESS)) {
++        ASSERT(false && "DuplicateHandle failed!");
++    }
++    return ret;
++}
++
++// It's safe to truncate a handle from 64-bits to 32-bits, or to sign-extend it
++// back to 64-bits.  See the MSDN article, "Interprocess Communication Between
++// 32-bit and 64-bit Applications".
++// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203.aspx
++static int64_t int64FromHandle(HANDLE h) {
++    return static_cast<int64_t>(reinterpret_cast<intptr_t>(h));
++}
++
++} // anonymous namespace
++
++Agent::Agent(LPCWSTR controlPipeName,
++             uint64_t agentFlags,
++             int mouseMode,
++             int initialCols,
++             int initialRows) :
++    m_useConerr((agentFlags & WINPTY_FLAG_CONERR) != 0),
++    m_plainMode((agentFlags & WINPTY_FLAG_PLAIN_OUTPUT) != 0),
++    m_mouseMode(mouseMode)
++{
++    trace("Agent::Agent entered");
++
++    ASSERT(initialCols >= 1 && initialRows >= 1);
++    initialCols = std::min(initialCols, MAX_CONSOLE_WIDTH);
++    initialRows = std::min(initialRows, MAX_CONSOLE_HEIGHT);
++
++    const bool outputColor =
++        !m_plainMode || (agentFlags & WINPTY_FLAG_COLOR_ESCAPES);
++    const Coord initialSize(initialCols, initialRows);
++
++    auto primaryBuffer = openPrimaryBuffer();
++    if (m_useConerr) {
++        m_errorBuffer = Win32ConsoleBuffer::createErrorBuffer();
++    }
++
++    detectNewWindows10Console(m_console, *primaryBuffer);
++
++    m_controlPipe = &connectToControlPipe(controlPipeName);
++    m_coninPipe = &createDataServerPipe(false, L"conin");
++    m_conoutPipe = &createDataServerPipe(true, L"conout");
++    if (m_useConerr) {
++        m_conerrPipe = &createDataServerPipe(true, L"conerr");
++    }
++
++    // Send an initial response packet to winpty.dll containing pipe names.
++    {
++        auto setupPacket = newPacket();
++        setupPacket.putWString(m_coninPipe->name());
++        setupPacket.putWString(m_conoutPipe->name());
++        if (m_useConerr) {
++            setupPacket.putWString(m_conerrPipe->name());
++        }
++        writePacket(setupPacket);
++    }
++
++    std::unique_ptr<Terminal> primaryTerminal;
++    primaryTerminal.reset(new Terminal(*m_conoutPipe,
++                                       m_plainMode,
++                                       outputColor));
++    m_primaryScraper.reset(new Scraper(m_console,
++                                       *primaryBuffer,
++                                       std::move(primaryTerminal),
++                                       initialSize));
++    if (m_useConerr) {
++        std::unique_ptr<Terminal> errorTerminal;
++        errorTerminal.reset(new Terminal(*m_conerrPipe,
++                                         m_plainMode,
++                                         outputColor));
++        m_errorScraper.reset(new Scraper(m_console,
++                                         *m_errorBuffer,
++                                         std::move(errorTerminal),
++                                         initialSize));
++    }
++
++    m_console.setTitle(m_currentTitle);
++
++    const HANDLE conin = GetStdHandle(STD_INPUT_HANDLE);
++    m_consoleInput.reset(
++        new ConsoleInput(conin, m_mouseMode, *this, m_console));
++
++    // Setup Ctrl-C handling.  First restore default handling of Ctrl-C.  This
++    // attribute is inherited by child processes.  Then register a custom
++    // Ctrl-C handler that does nothing.  The handler will be called when the
++    // agent calls GenerateConsoleCtrlEvent.
++    SetConsoleCtrlHandler(NULL, FALSE);
++    SetConsoleCtrlHandler(consoleCtrlHandler, TRUE);
++
++    setPollInterval(25);
++}
++
++Agent::~Agent()
++{
++    trace("Agent::~Agent entered");
++    agentShutdown();
++    if (m_childProcess != NULL) {
++        CloseHandle(m_childProcess);
++    }
++}
++
++// Write a "Device Status Report" command to the terminal.  The terminal will
++// reply with a row+col escape sequence.  Presumably, the DSR reply will not
++// split a keypress escape sequence, so it should be safe to assume that the
++// bytes before it are complete keypresses.
++void Agent::sendDsr()
++{
++    if (!m_plainMode && !m_conoutPipe->isClosed()) {
++        m_conoutPipe->write("\x1B[6n");
++    }
++}
++
++NamedPipe &Agent::connectToControlPipe(LPCWSTR pipeName)
++{
++    NamedPipe &pipe = createNamedPipe();
++    pipe.connectToServer(pipeName, NamedPipe::OpenMode::Duplex);
++    pipe.setReadBufferSize(64 * 1024);
++    return pipe;
++}
++
++// Returns a new server named pipe.  It has not yet been connected.
++NamedPipe &Agent::createDataServerPipe(bool write, const wchar_t *kind)
++{
++    const auto name =
++        (WStringBuilder(128)
++            << L"\\\\.\\pipe\\winpty-"
++            << kind << L'-'
++            << GenRandom().uniqueName()).str_moved();
++    NamedPipe &pipe = createNamedPipe();
++    pipe.openServerPipe(
++        name.c_str(),
++        write ? NamedPipe::OpenMode::Writing
++              : NamedPipe::OpenMode::Reading,
++        write ? 8192 : 0,
++        write ? 0 : 256);
++    if (!write) {
++        pipe.setReadBufferSize(64 * 1024);
++    }
++    return pipe;
++}
++
++void Agent::onPipeIo(NamedPipe &namedPipe)
++{
++    if (&namedPipe == m_conoutPipe || &namedPipe == m_conerrPipe) {
++        autoClosePipesForShutdown();
++    } else if (&namedPipe == m_coninPipe) {
++        pollConinPipe();
++    } else if (&namedPipe == m_controlPipe) {
++        pollControlPipe();
++    }
++}
++
++void Agent::pollControlPipe()
++{
++    if (m_controlPipe->isClosed()) {
++        trace("Agent exiting (control pipe is closed)");
++        shutdown();
++        return;
++    }
++
++    while (true) {
++        uint64_t packetSize = 0;
++        const auto amt1 =
++            m_controlPipe->peek(&packetSize, sizeof(packetSize));
++        if (amt1 < sizeof(packetSize)) {
++            break;
++        }
++        ASSERT(packetSize >= sizeof(packetSize) && packetSize <= SIZE_MAX);
++        if (m_controlPipe->bytesAvailable() < packetSize) {
++            if (m_controlPipe->readBufferSize() < packetSize) {
++                m_controlPipe->setReadBufferSize(packetSize);
++            }
++            break;
++        }
++        std::vector<char> packetData;
++        packetData.resize(packetSize);
++        const auto amt2 = m_controlPipe->read(packetData.data(), packetSize);
++        ASSERT(amt2 == packetSize);
++        try {
++            ReadBuffer buffer(std::move(packetData));
++            buffer.getRawValue<uint64_t>(); // Discard the size.
++            handlePacket(buffer);
++        } catch (const ReadBuffer::DecodeError&) {
++            ASSERT(false && "Decode error");
++        }
++    }
++}
++
++void Agent::handlePacket(ReadBuffer &packet)
++{
++    const int type = packet.getInt32();
++    switch (type) {
++    case AgentMsg::StartProcess:
++        handleStartProcessPacket(packet);
++        break;
++    case AgentMsg::SetSize:
++        // TODO: I think it might make sense to collapse consecutive SetSize
++        // messages.  i.e. The terminal process can probably generate SetSize
++        // messages faster than they can be processed, and some GUIs might
++        // generate a flood of them, so if we can read multiple SetSize packets
++        // at once, we can ignore the early ones.
++        handleSetSizePacket(packet);
++        break;
++    case AgentMsg::GetConsoleProcessList:
++        handleGetConsoleProcessListPacket(packet);
++        break;
++    default:
++        trace("Unrecognized message, id:%d", type);
++    }
++}
++
++void Agent::writePacket(WriteBuffer &packet)
++{
++    const auto &bytes = packet.buf();
++    packet.replaceRawValue<uint64_t>(0, bytes.size());
++    m_controlPipe->write(bytes.data(), bytes.size());
++}
++
++void Agent::handleStartProcessPacket(ReadBuffer &packet)
++{
++    ASSERT(m_childProcess == nullptr);
++    ASSERT(!m_closingOutputPipes);
++
++    const uint64_t spawnFlags = packet.getInt64();
++    const bool wantProcessHandle = packet.getInt32() != 0;
++    const bool wantThreadHandle = packet.getInt32() != 0;
++    const auto program = packet.getWString();
++    const auto cmdline = packet.getWString();
++    const auto cwd = packet.getWString();
++    const auto env = packet.getWString();
++    const auto desktop = packet.getWString();
++    packet.assertEof();
++
++    auto cmdlineV = vectorWithNulFromString(cmdline);
++    auto desktopV = vectorWithNulFromString(desktop);
++    auto envV = vectorFromString(env);
++
++    LPCWSTR programArg = program.empty() ? nullptr : program.c_str();
++    LPWSTR cmdlineArg = cmdline.empty() ? nullptr : cmdlineV.data();
++    LPCWSTR cwdArg = cwd.empty() ? nullptr : cwd.c_str();
++    LPWSTR envArg = env.empty() ? nullptr : envV.data();
++
++    STARTUPINFOW sui = {};
++    PROCESS_INFORMATION pi = {};
++    sui.cb = sizeof(sui);
++    sui.lpDesktop = desktop.empty() ? nullptr : desktopV.data();
++    BOOL inheritHandles = FALSE;
++    if (m_useConerr) {
++        inheritHandles = TRUE;
++        sui.dwFlags |= STARTF_USESTDHANDLES;
++        sui.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
++        sui.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
++        sui.hStdError = m_errorBuffer->conout();
++    }
++
++    const BOOL success =
++        CreateProcessW(programArg, cmdlineArg, nullptr, nullptr,
++                       /*bInheritHandles=*/inheritHandles,
++                       /*dwCreationFlags=*/CREATE_UNICODE_ENVIRONMENT,
++                       envArg, cwdArg, &sui, &pi);
++    const int lastError = success ? 0 : GetLastError();
++
++    trace("CreateProcess: %s %u",
++          (success ? "success" : "fail"),
++          static_cast<unsigned int>(pi.dwProcessId));
++
++    auto reply = newPacket();
++    if (success) {
++        int64_t replyProcess = 0;
++        int64_t replyThread = 0;
++        if (wantProcessHandle) {
++            replyProcess = int64FromHandle(duplicateHandle(pi.hProcess));
++        }
++        if (wantThreadHandle) {
++            replyThread = int64FromHandle(duplicateHandle(pi.hThread));
++        }
++        CloseHandle(pi.hThread);
++        m_childProcess = pi.hProcess;
++        m_autoShutdown = (spawnFlags & WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN) != 0;
++        m_exitAfterShutdown = (spawnFlags & WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN) != 0;
++        reply.putInt32(static_cast<int32_t>(StartProcessResult::ProcessCreated));
++        reply.putInt64(replyProcess);
++        reply.putInt64(replyThread);
++    } else {
++        reply.putInt32(static_cast<int32_t>(StartProcessResult::CreateProcessFailed));
++        reply.putInt32(lastError);
++    }
++    writePacket(reply);
++}
++
++void Agent::handleSetSizePacket(ReadBuffer &packet)
++{
++    const int cols = packet.getInt32();
++    const int rows = packet.getInt32();
++    packet.assertEof();
++    resizeWindow(cols, rows);
++    auto reply = newPacket();
++    writePacket(reply);
++}
++
++void Agent::handleGetConsoleProcessListPacket(ReadBuffer &packet)
++{
++    packet.assertEof();
++
++    auto processList = std::vector<DWORD>(64);
++    auto processCount = GetConsoleProcessList(&processList[0], processList.size());
++    if (processList.size() < processCount) {
++        processList.resize(processCount);
++        processCount = GetConsoleProcessList(&processList[0], processList.size());
++    }
++
++    if (processCount == 0) {
++        trace("GetConsoleProcessList failed");
++    }
++
++    auto reply = newPacket();
++    reply.putInt32(processCount);
++    for (DWORD i = 0; i < processCount; i++) {
++        reply.putInt32(processList[i]);
++    }
++    writePacket(reply);
++}
++
++void Agent::pollConinPipe()
++{
++    const std::string newData = m_coninPipe->readAllToString();
++    if (hasDebugFlag("input_separated_bytes")) {
++        // This debug flag is intended to help with testing incomplete escape
++        // sequences and multibyte UTF-8 encodings.  (I wonder if the normal
++        // code path ought to advance a state machine one byte at a time.)
++        for (size_t i = 0; i < newData.size(); ++i) {
++            m_consoleInput->writeInput(newData.substr(i, 1));
++        }
++    } else {
++        m_consoleInput->writeInput(newData);
++    }
++}
++
++void Agent::onPollTimeout()
++{
++    m_consoleInput->updateInputFlags();
++    const bool enableMouseMode = m_consoleInput->shouldActivateTerminalMouse();
++
++    // Give the ConsoleInput object a chance to flush input from an incomplete
++    // escape sequence (e.g. pressing ESC).
++    m_consoleInput->flushIncompleteEscapeCode();
++
++    const bool shouldScrapeContent = !m_closingOutputPipes;
++
++    // Check if the child process has exited.
++    if (m_autoShutdown &&
++            m_childProcess != nullptr &&
++            WaitForSingleObject(m_childProcess, 0) == WAIT_OBJECT_0) {
++        CloseHandle(m_childProcess);
++        m_childProcess = nullptr;
++
++        // Close the data socket to signal to the client that the child
++        // process has exited.  If there's any data left to send, send it
++        // before closing the socket.
++        m_closingOutputPipes = true;
++    }
++
++    // Scrape for output *after* the above exit-check to ensure that we collect
++    // the child process's final output.
++    if (shouldScrapeContent) {
++        syncConsoleTitle();
++        scrapeBuffers();
++    }
++
++    // We must ensure that we disable mouse mode before closing the CONOUT
++    // pipe, so update the mouse mode here.
++    m_primaryScraper->terminal().enableMouseMode(
++        enableMouseMode && !m_closingOutputPipes);
++
++    autoClosePipesForShutdown();
++}
++
++void Agent::autoClosePipesForShutdown()
++{
++    if (m_closingOutputPipes) {
++        // We don't want to close a pipe before it's connected!  If we do, the
++        // libwinpty client may try to connect to a non-existent pipe.  This
++        // case is important for short-lived programs.
++        if (m_conoutPipe->isConnected() &&
++                m_conoutPipe->bytesToSend() == 0) {
++            trace("Closing CONOUT pipe (auto-shutdown)");
++            m_conoutPipe->closePipe();
++        }
++        if (m_conerrPipe != nullptr &&
++                m_conerrPipe->isConnected() &&
++                m_conerrPipe->bytesToSend() == 0) {
++            trace("Closing CONERR pipe (auto-shutdown)");
++            m_conerrPipe->closePipe();
++        }
++        if (m_exitAfterShutdown &&
++                m_conoutPipe->isClosed() &&
++                (m_conerrPipe == nullptr || m_conerrPipe->isClosed())) {
++            trace("Agent exiting (exit-after-shutdown)");
++            shutdown();
++        }
++    }
++}
++
++std::unique_ptr<Win32ConsoleBuffer> Agent::openPrimaryBuffer()
++{
++    // If we're using a separate buffer for stderr, and a program were to
++    // activate the stderr buffer, then we could accidentally scrape the same
++    // buffer twice.  That probably shouldn't happen in ordinary use, but it
++    // can be avoided anyway by using the original console screen buffer in
++    // that mode.
++    if (!m_useConerr) {
++        return Win32ConsoleBuffer::openConout();
++    } else {
++        return Win32ConsoleBuffer::openStdout();
++    }
++}
++
++void Agent::resizeWindow(int cols, int rows)
++{
++    ASSERT(cols >= 1 && rows >= 1);
++    cols = std::min(cols, MAX_CONSOLE_WIDTH);
++    rows = std::min(rows, MAX_CONSOLE_HEIGHT);
++
++    Win32Console::FreezeGuard guard(m_console, m_console.frozen());
++    const Coord newSize(cols, rows);
++    ConsoleScreenBufferInfo info;
++    auto primaryBuffer = openPrimaryBuffer();
++    m_primaryScraper->resizeWindow(*primaryBuffer, newSize, info);
++    m_consoleInput->setMouseWindowRect(info.windowRect());
++    if (m_errorScraper) {
++        m_errorScraper->resizeWindow(*m_errorBuffer, newSize, info);
++    }
++
++    // Synthesize a WINDOW_BUFFER_SIZE_EVENT event.  Normally, Windows
++    // generates this event only when the buffer size changes, not when the
++    // window size changes.  This behavior is undesirable in two ways:
++    //  - When winpty expands the window horizontally, it must expand the
++    //    buffer first, then the window.  At least some programs (e.g. the WSL
++    //    bash.exe wrapper) use the window width rather than the buffer width,
++    //    so there is a short timespan during which they can read the wrong
++    //    value.
++    //  - If the window's vertical size is changed, no event is generated,
++    //    even though a typical well-behaved console program cares about the
++    //    *window* height, not the *buffer* height.
++    // This synthesization works around a design flaw in the console.  It's probably
++    // harmless.  See https://github.com/rprichard/winpty/issues/110.
++    INPUT_RECORD sizeEvent {};
++    sizeEvent.EventType = WINDOW_BUFFER_SIZE_EVENT;
++    sizeEvent.Event.WindowBufferSizeEvent.dwSize = primaryBuffer->bufferSize();
++    DWORD actual {};
++    WriteConsoleInputW(GetStdHandle(STD_INPUT_HANDLE), &sizeEvent, 1, &actual);
++}
++
++void Agent::scrapeBuffers()
++{
++    Win32Console::FreezeGuard guard(m_console, m_console.frozen());
++    ConsoleScreenBufferInfo info;
++    m_primaryScraper->scrapeBuffer(*openPrimaryBuffer(), info);
++    m_consoleInput->setMouseWindowRect(info.windowRect());
++    if (m_errorScraper) {
++        m_errorScraper->scrapeBuffer(*m_errorBuffer, info);
++    }
++}
++
++void Agent::syncConsoleTitle()
++{
++    std::wstring newTitle = m_console.title();
++    if (newTitle != m_currentTitle) {
++        std::string command = std::string("\x1b]0;") +
++                utf8FromWide(newTitle) + "\x07";
++        m_conoutPipe->write(command.c_str());
++        m_currentTitle = newTitle;
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1dde48fe4abe51484b143c41419403ad6013061e
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,103 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_H
++#define AGENT_H
++
++#include <windows.h>
++#include <stdint.h>
++
++#include <memory>
++#include <string>
++
++#include "DsrSender.h"
++#include "EventLoop.h"
++#include "Win32Console.h"
++
++class ConsoleInput;
++class NamedPipe;
++class ReadBuffer;
++class Scraper;
++class WriteBuffer;
++class Win32ConsoleBuffer;
++
++class Agent : public EventLoop, public DsrSender
++{
++public:
++    Agent(LPCWSTR controlPipeName,
++          uint64_t agentFlags,
++          int mouseMode,
++          int initialCols,
++          int initialRows);
++    virtual ~Agent();
++    void sendDsr() override;
++
++private:
++    NamedPipe &connectToControlPipe(LPCWSTR pipeName);
++    NamedPipe &createDataServerPipe(bool write, const wchar_t *kind);
++
++private:
++    void pollControlPipe();
++    void handlePacket(ReadBuffer &packet);
++    void writePacket(WriteBuffer &packet);
++    void handleStartProcessPacket(ReadBuffer &packet);
++    void handleSetSizePacket(ReadBuffer &packet);
++    void handleGetConsoleProcessListPacket(ReadBuffer &packet);
++    void pollConinPipe();
++
++protected:
++    virtual void onPollTimeout() override;
++    virtual void onPipeIo(NamedPipe &namedPipe) override;
++
++private:
++    void autoClosePipesForShutdown();
++    std::unique_ptr<Win32ConsoleBuffer> openPrimaryBuffer();
++    void resizeWindow(int cols, int rows);
++    void scrapeBuffers();
++    void syncConsoleTitle();
++
++private:
++    const bool m_useConerr;
++    const bool m_plainMode;
++    const int m_mouseMode;
++    Win32Console m_console;
++    std::unique_ptr<Scraper> m_primaryScraper;
++    std::unique_ptr<Scraper> m_errorScraper;
++    std::unique_ptr<Win32ConsoleBuffer> m_errorBuffer;
++    NamedPipe *m_controlPipe = nullptr;
++    NamedPipe *m_coninPipe = nullptr;
++    NamedPipe *m_conoutPipe = nullptr;
++    NamedPipe *m_conerrPipe = nullptr;
++    bool m_autoShutdown = false;
++    bool m_exitAfterShutdown = false;
++    bool m_closingOutputPipes = false;
++    std::unique_ptr<ConsoleInput> m_consoleInput;
++    HANDLE m_childProcess = nullptr;
++
++    // If the title is initialized to the empty string, then cmd.exe will
++    // sometimes print this error:
++    //     Not enough storage is available to process this command.
++    // It happens on Windows 7 when logged into a Cygwin SSH session, for
++    // example.  Using a title of a single space character avoids the problem.
++    // See https://github.com/rprichard/winpty/issues/74.
++    std::wstring m_currentTitle = L" ";
++};
++
++#endif // AGENT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9ad6503b1c5a460daf46aa1efa0def48d976a96e
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,84 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "AgentCreateDesktop.h"
++
++#include "../shared/BackgroundDesktop.h"
++#include "../shared/Buffer.h"
++#include "../shared/DebugClient.h"
++#include "../shared/StringUtil.h"
++
++#include "EventLoop.h"
++#include "NamedPipe.h"
++
++namespace {
++
++static inline WriteBuffer newPacket() {
++    WriteBuffer packet;
++    packet.putRawValue<uint64_t>(0); // Reserve space for size.
++    return packet;
++}
++
++class CreateDesktopLoop : public EventLoop {
++public:
++    CreateDesktopLoop(LPCWSTR controlPipeName);
++
++protected:
++    virtual void onPipeIo(NamedPipe &namedPipe) override;
++
++private:
++    void writePacket(WriteBuffer &packet);
++
++    BackgroundDesktop m_desktop;
++    NamedPipe &m_pipe;
++};
++
++CreateDesktopLoop::CreateDesktopLoop(LPCWSTR controlPipeName) :
++        m_pipe(createNamedPipe()) {
++    m_pipe.connectToServer(controlPipeName, NamedPipe::OpenMode::Duplex);
++    auto packet = newPacket();
++    packet.putWString(m_desktop.desktopName());
++    writePacket(packet);
++}
++
++void CreateDesktopLoop::writePacket(WriteBuffer &packet) {
++    const auto &bytes = packet.buf();
++    packet.replaceRawValue<uint64_t>(0, bytes.size());
++    m_pipe.write(bytes.data(), bytes.size());
++}
++
++void CreateDesktopLoop::onPipeIo(NamedPipe &namedPipe) {
++    if (m_pipe.isClosed()) {
++        shutdown();
++    }
++}
++
++} // anonymous namespace
++
++void handleCreateDesktop(LPCWSTR controlPipeName) {
++    try {
++        CreateDesktopLoop loop(controlPipeName);
++        loop.run();
++        trace("Agent exiting...");
++    } catch (const WinptyException &e) {
++        trace("handleCreateDesktop: internal error: %s",
++            utf8FromWide(e.what()).c_str());
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2ae539c7faadeda338ff0d76e03eb69bc217f39f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,28 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_CREATE_DESKTOP_H
++#define AGENT_CREATE_DESKTOP_H
++
++#include <windows.h>
++
++void handleCreateDesktop(LPCWSTR controlPipeName);
++
++#endif //  AGENT_CREATE_DESKTOP_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..aa1f7876d3807ddb631b449419a7b8bc7b708399
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,698 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "ConsoleFont.h"
++
++#include <windows.h>
++#include <stdio.h>
++#include <string.h>
++#include <wchar.h>
++
++#include <algorithm>
++#include <string>
++#include <tuple>
++#include <utility>
++#include <vector>
++
++#include "../shared/DebugClient.h"
++#include "../shared/OsModule.h"
++#include "../shared/StringUtil.h"
++#include "../shared/WindowsVersion.h"
++#include "../shared/WinptyAssert.h"
++#include "../shared/winpty_snprintf.h"
++
++namespace {
++
++#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
++
++// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
++const wchar_t kLucidaConsole[] = L"Lucida Console";
++const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // 932, Japanese
++const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // 936, Chinese Simplified
++const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // 949, Korean
++const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // 950, Chinese Traditional
++
++struct FontSize {
++    short size;
++    int width;
++};
++
++struct Font {
++    const wchar_t *faceName;
++    unsigned int family;
++    short size;
++};
++
++// Ideographs in East Asian languages take two columns rather than one.
++// In the console screen buffer, a "full-width" character will occupy two
++// cells of the buffer, the first with attribute 0x100 and the second with
++// attribute 0x200.
++//
++// Windows does not correctly identify code points as double-width in all
++// configurations.  It depends heavily on the code page, the font facename,
++// and (somehow) even the font size.  In the 437 code page (MS-DOS), for
++// example, no codepoints are interpreted as double-width.  When the console
++// is in an East Asian code page (932, 936, 949, or 950), then sometimes
++// selecting a "Western" facename like "Lucida Console" or "Consolas" doesn't
++// register, or if the font *can* be chosen, then the console doesn't handle
++// double-width correctly.  I tested the double-width handling by writing
++// several code points with WriteConsole and checking whether one or two cells
++// were filled.
++//
++// In the Japanese code page (932), Microsoft's default font is MS Gothic.
++// MS Gothic double-width handling seems to be broken with console versions
++// prior to Windows 10 (including Windows 10's legacy mode), and it's
++// especially broken in Windows 8 and 8.1.
++//
++// Test by running: misc/Utf16Echo A2 A3 2014 3044 30FC 4000
++//
++// The first three codepoints are always rendered as half-width with the
++// Windows Japanese fonts.  (Of these, the first two must be half-width,
++// but U+2014 could be either.)  The last three are rendered as full-width,
++// and they are East_Asian_Width=Wide.
++//
++// Windows 7 fails by modeling all codepoints as full-width with font
++// sizes 22 and above.
++//
++// Windows 8 gets U+00A2, U+00A3, U+2014, U+30FC, and U+4000 wrong, but
++// using a point size not listed in the console properties dialog
++// (e.g. "9") is less wrong:
++//
++//             |        code point               |
++//  font       | 00A2 00A3 2014 3044 30FC 4000   | cell size
++// ------------+---------------------------------+----------
++//  8          |  F    F    F    F    H    H     |   4x8
++//  9          |  F    F    F    F    F    F     |   5x9
++//  16         |  F    F    F    F    H    H     |   8x16
++// raster 6x13 |  H    H    H    F    F    H(*)  |   6x13
++//
++// (*) The Raster Font renders U+4000 as a white box (i.e. an unsupported
++// character).
++//
++
++// See:
++//  - misc/Font-Report-June2016 directory for per-size details
++//  - misc/font-notes.txt
++//  - misc/Utf16Echo.cc, misc/FontSurvey.cc, misc/SetFont.cc, misc/GetFont.cc
++
++const FontSize kLucidaFontSizes[] = {
++    { 5, 3 },
++    { 6, 4 },
++    { 8, 5 },
++    { 10, 6 },
++    { 12, 7 },
++    { 14, 8 },
++    { 16, 10 },
++    { 18, 11 },
++    { 20, 12 },
++    { 36, 22 },
++    { 48, 29 },
++    { 60, 36 },
++    { 72, 43 },
++};
++
++// Japanese.  Used on Vista and Windows 7.
++const FontSize k932GothicVista[] = {
++    { 6, 3 },
++    { 8, 4 },
++    { 10, 5 },
++    { 12, 6 },
++    { 13, 7 },
++    { 15, 8 },
++    { 17, 9 },
++    { 19, 10 },
++    { 21, 11 },
++    // All larger fonts are more broken w.r.t. full-size East Asian characters.
++};
++
++// Japanese.  Used on Windows 8, 8.1, and the legacy 10 console.
++const FontSize k932GothicWin8[] = {
++    // All of these characters are broken w.r.t. full-size East Asian
++    // characters, but they're equally broken.
++    { 5, 3 },
++    { 7, 4 },
++    { 9, 5 },
++    { 11, 6 },
++    { 13, 7 },
++    { 15, 8 },
++    { 17, 9 },
++    { 20, 10 },
++    { 22, 11 },
++    { 24, 12 },
++    // include extra-large fonts for small terminals
++    { 36, 18 },
++    { 48, 24 },
++    { 60, 30 },
++    { 72, 36 },
++};
++
++// Japanese.  Used on the new Windows 10 console.
++const FontSize k932GothicWin10[] = {
++    { 6, 3 },
++    { 8, 4 },
++    { 10, 5 },
++    { 12, 6 },
++    { 14, 7 },
++    { 16, 8 },
++    { 18, 9 },
++    { 20, 10 },
++    { 22, 11 },
++    { 24, 12 },
++    // include extra-large fonts for small terminals
++    { 36, 18 },
++    { 48, 24 },
++    { 60, 30 },
++    { 72, 36 },
++};
++
++// Chinese Simplified.
++const FontSize k936SimSun[] = {
++    { 6, 3 },
++    { 8, 4 },
++    { 10, 5 },
++    { 12, 6 },
++    { 14, 7 },
++    { 16, 8 },
++    { 18, 9 },
++    { 20, 10 },
++    { 22, 11 },
++    { 24, 12 },
++    // include extra-large fonts for small terminals
++    { 36, 18 },
++    { 48, 24 },
++    { 60, 30 },
++    { 72, 36 },
++};
++
++// Korean.
++const FontSize k949GulimChe[] = {
++    { 6, 3 },
++    { 8, 4 },
++    { 10, 5 },
++    { 12, 6 },
++    { 14, 7 },
++    { 16, 8 },
++    { 18, 9 },
++    { 20, 10 },
++    { 22, 11 },
++    { 24, 12 },
++    // include extra-large fonts for small terminals
++    { 36, 18 },
++    { 48, 24 },
++    { 60, 30 },
++    { 72, 36 },
++};
++
++// Chinese Traditional.
++const FontSize k950MingLight[] = {
++    { 6, 3 },
++    { 8, 4 },
++    { 10, 5 },
++    { 12, 6 },
++    { 14, 7 },
++    { 16, 8 },
++    { 18, 9 },
++    { 20, 10 },
++    { 22, 11 },
++    { 24, 12 },
++    // include extra-large fonts for small terminals
++    { 36, 18 },
++    { 48, 24 },
++    { 60, 30 },
++    { 72, 36 },
++};
++
++// Some of these types and functions are missing from the MinGW headers.
++// Others are undocumented.
++
++struct AGENT_CONSOLE_FONT_INFO {
++    DWORD nFont;
++    COORD dwFontSize;
++};
++
++struct AGENT_CONSOLE_FONT_INFOEX {
++    ULONG cbSize;
++    DWORD nFont;
++    COORD dwFontSize;
++    UINT FontFamily;
++    UINT FontWeight;
++    WCHAR FaceName[LF_FACESIZE];
++};
++
++// undocumented XP API
++typedef BOOL WINAPI SetConsoleFont_t(
++            HANDLE hOutput,
++            DWORD dwFontIndex);
++
++// undocumented XP API
++typedef DWORD WINAPI GetNumberOfConsoleFonts_t();
++
++// XP and up
++typedef BOOL WINAPI GetCurrentConsoleFont_t(
++            HANDLE hOutput,
++            BOOL bMaximumWindow,
++            AGENT_CONSOLE_FONT_INFO *lpConsoleCurrentFont);
++
++// XP and up
++typedef COORD WINAPI GetConsoleFontSize_t(
++            HANDLE hConsoleOutput,
++            DWORD nFont);
++
++// Vista and up
++typedef BOOL WINAPI GetCurrentConsoleFontEx_t(
++            HANDLE hConsoleOutput,
++            BOOL bMaximumWindow,
++            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
++
++// Vista and up
++typedef BOOL WINAPI SetCurrentConsoleFontEx_t(
++            HANDLE hConsoleOutput,
++            BOOL bMaximumWindow,
++            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
++
++#define GET_MODULE_PROC(mod, funcName) \
++    m_##funcName = reinterpret_cast<funcName##_t*>((mod).proc(#funcName)); \
++
++#define DEFINE_ACCESSOR(funcName) \
++    funcName##_t &funcName() const { \
++        ASSERT(valid()); \
++        return *m_##funcName; \
++    }
++
++class XPFontAPI {
++public:
++    XPFontAPI() : m_kernel32(L"kernel32.dll") {
++        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFont);
++        GET_MODULE_PROC(m_kernel32, GetConsoleFontSize);
++    }
++
++    bool valid() const {
++        return m_GetCurrentConsoleFont != NULL &&
++            m_GetConsoleFontSize != NULL;
++    }
++
++    DEFINE_ACCESSOR(GetCurrentConsoleFont)
++    DEFINE_ACCESSOR(GetConsoleFontSize)
++
++private:
++    OsModule m_kernel32;
++    GetCurrentConsoleFont_t *m_GetCurrentConsoleFont;
++    GetConsoleFontSize_t *m_GetConsoleFontSize;
++};
++
++class UndocumentedXPFontAPI : public XPFontAPI {
++public:
++    UndocumentedXPFontAPI() : m_kernel32(L"kernel32.dll") {
++        GET_MODULE_PROC(m_kernel32, SetConsoleFont);
++        GET_MODULE_PROC(m_kernel32, GetNumberOfConsoleFonts);
++    }
++
++    bool valid() const {
++        return this->XPFontAPI::valid() &&
++            m_SetConsoleFont != NULL &&
++            m_GetNumberOfConsoleFonts != NULL;
++    }
++
++    DEFINE_ACCESSOR(SetConsoleFont)
++    DEFINE_ACCESSOR(GetNumberOfConsoleFonts)
++
++private:
++    OsModule m_kernel32;
++    SetConsoleFont_t *m_SetConsoleFont;
++    GetNumberOfConsoleFonts_t *m_GetNumberOfConsoleFonts;
++};
++
++class VistaFontAPI : public XPFontAPI {
++public:
++    VistaFontAPI() : m_kernel32(L"kernel32.dll") {
++        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFontEx);
++        GET_MODULE_PROC(m_kernel32, SetCurrentConsoleFontEx);
++    }
++
++    bool valid() const {
++        return this->XPFontAPI::valid() &&
++            m_GetCurrentConsoleFontEx != NULL &&
++            m_SetCurrentConsoleFontEx != NULL;
++    }
++
++    DEFINE_ACCESSOR(GetCurrentConsoleFontEx)
++    DEFINE_ACCESSOR(SetCurrentConsoleFontEx)
++
++private:
++    OsModule m_kernel32;
++    GetCurrentConsoleFontEx_t *m_GetCurrentConsoleFontEx;
++    SetCurrentConsoleFontEx_t *m_SetCurrentConsoleFontEx;
++};
++
++static std::vector<std::pair<DWORD, COORD> > readFontTable(
++        XPFontAPI &api, HANDLE conout, DWORD maxCount) {
++    std::vector<std::pair<DWORD, COORD> > ret;
++    for (DWORD i = 0; i < maxCount; ++i) {
++        COORD size = api.GetConsoleFontSize()(conout, i);
++        if (size.X == 0 && size.Y == 0) {
++            break;
++        }
++        ret.push_back(std::make_pair(i, size));
++    }
++    return ret;
++}
++
++static void dumpFontTable(HANDLE conout, const char *prefix) {
++    const int kMaxCount = 1000;
++    if (!isTracingEnabled()) {
++        return;
++    }
++    XPFontAPI api;
++    if (!api.valid()) {
++        trace("dumpFontTable: cannot dump font table -- missing APIs");
++        return;
++    }
++    std::vector<std::pair<DWORD, COORD> > table =
++        readFontTable(api, conout, kMaxCount);
++    std::string line;
++    char tmp[128];
++    size_t first = 0;
++    while (first < table.size()) {
++        size_t last = std::min(table.size() - 1, first + 10 - 1);
++        winpty_snprintf(tmp, "%sfonts %02u-%02u:",
++            prefix, static_cast<unsigned>(first), static_cast<unsigned>(last));
++        line = tmp;
++        for (size_t i = first; i <= last; ++i) {
++            if (i % 10 == 5) {
++                line += "  - ";
++            }
++            winpty_snprintf(tmp, " %2dx%-2d",
++                table[i].second.X, table[i].second.Y);
++            line += tmp;
++        }
++        trace("%s", line.c_str());
++        first = last + 1;
++    }
++    if (table.size() == kMaxCount) {
++        trace("%sfonts: ... stopped reading at %d fonts ...",
++            prefix, kMaxCount);
++    }
++}
++
++static std::string stringToCodePoints(const std::wstring &str) {
++    std::string ret = "(";
++    for (size_t i = 0; i < str.size(); ++i) {
++        char tmp[32];
++        winpty_snprintf(tmp, "%X", str[i]);
++        if (ret.size() > 1) {
++            ret.push_back(' ');
++        }
++        ret += tmp;
++    }
++    ret.push_back(')');
++    return ret;
++}
++
++static void dumpFontInfoEx(
++        const AGENT_CONSOLE_FONT_INFOEX &infoex,
++        const char *prefix) {
++    if (!isTracingEnabled()) {
++        return;
++    }
++    std::wstring faceName(infoex.FaceName,
++        winpty_wcsnlen(infoex.FaceName, COUNT_OF(infoex.FaceName)));
++    trace("%snFont=%u dwFontSize=(%d,%d) "
++        "FontFamily=0x%x FontWeight=%u FaceName=%s %s",
++        prefix,
++        static_cast<unsigned>(infoex.nFont),
++        infoex.dwFontSize.X, infoex.dwFontSize.Y,
++        infoex.FontFamily, infoex.FontWeight, utf8FromWide(faceName).c_str(),
++        stringToCodePoints(faceName).c_str());
++}
++
++static void dumpVistaFont(VistaFontAPI &api, HANDLE conout, const char *prefix) {
++    if (!isTracingEnabled()) {
++        return;
++    }
++    AGENT_CONSOLE_FONT_INFOEX infoex = {0};
++    infoex.cbSize = sizeof(infoex);
++    if (!api.GetCurrentConsoleFontEx()(conout, FALSE, &infoex)) {
++        trace("GetCurrentConsoleFontEx call failed");
++        return;
++    }
++    dumpFontInfoEx(infoex, prefix);
++}
++
++static void dumpXPFont(XPFontAPI &api, HANDLE conout, const char *prefix) {
++    if (!isTracingEnabled()) {
++        return;
++    }
++    AGENT_CONSOLE_FONT_INFO info = {0};
++    if (!api.GetCurrentConsoleFont()(conout, FALSE, &info)) {
++        trace("GetCurrentConsoleFont call failed");
++        return;
++    }
++    trace("%snFont=%u dwFontSize=(%d,%d)",
++        prefix,
++        static_cast<unsigned>(info.nFont),
++        info.dwFontSize.X, info.dwFontSize.Y);
++}
++
++static bool setFontVista(
++        VistaFontAPI &api,
++        HANDLE conout,
++        const Font &font) {
++    AGENT_CONSOLE_FONT_INFOEX infoex = {};
++    infoex.cbSize = sizeof(AGENT_CONSOLE_FONT_INFOEX);
++    infoex.dwFontSize.Y = font.size;
++    infoex.FontFamily = font.family;
++    infoex.FontWeight = 400;
++    winpty_wcsncpy_nul(infoex.FaceName, font.faceName);
++    dumpFontInfoEx(infoex, "setFontVista: setting font to: ");
++    if (!api.SetCurrentConsoleFontEx()(conout, FALSE, &infoex)) {
++        trace("setFontVista: SetCurrentConsoleFontEx call failed");
++        return false;
++    }
++    memset(&infoex, 0, sizeof(infoex));
++    infoex.cbSize = sizeof(infoex);
++    if (!api.GetCurrentConsoleFontEx()(conout, FALSE, &infoex)) {
++        trace("setFontVista: GetCurrentConsoleFontEx call failed");
++        return false;
++    }
++    if (wcsncmp(infoex.FaceName, font.faceName,
++            COUNT_OF(infoex.FaceName)) != 0) {
++        trace("setFontVista: face name was not set");
++        dumpFontInfoEx(infoex, "setFontVista: post-call font: ");
++        return false;
++    }
++    // We'd like to verify that the new font size is correct, but we can't
++    // predict what it will be, even though we just set it to `pxSize` through
++    // an apprently symmetric interface.  For the Chinese and Korean fonts, the
++    // new `infoex.dwFontSize.Y` value can be slightly larger than the height
++    // we specified.
++    return true;
++}
++
++static Font selectSmallFont(int codePage, int columns, bool isNewW10) {
++    // Iterate over a set of font sizes according to the code page, and select
++    // one.
++
++    const wchar_t *faceName = nullptr;
++    unsigned int fontFamily = 0;
++    const FontSize *table = nullptr;
++    size_t tableSize = 0;
++
++    switch (codePage) {
++        case 932: // Japanese
++            faceName = kMSGothic;
++            fontFamily = 0x36;
++            if (isNewW10) {
++                table = k932GothicWin10;
++                tableSize = COUNT_OF(k932GothicWin10);
++            } else if (isAtLeastWindows8()) {
++                table = k932GothicWin8;
++                tableSize = COUNT_OF(k932GothicWin8);
++            } else {
++                table = k932GothicVista;
++                tableSize = COUNT_OF(k932GothicVista);
++            }
++            break;
++        case 936: // Chinese Simplified
++            faceName = kNSimSun;
++            fontFamily = 0x36;
++            table = k936SimSun;
++            tableSize = COUNT_OF(k936SimSun);
++            break;
++        case 949: // Korean
++            faceName = kGulimChe;
++            fontFamily = 0x36;
++            table = k949GulimChe;
++            tableSize = COUNT_OF(k949GulimChe);
++            break;
++        case 950: // Chinese Traditional
++            faceName = kMingLight;
++            fontFamily = 0x36;
++            table = k950MingLight;
++            tableSize = COUNT_OF(k950MingLight);
++            break;
++        default:
++            faceName = kLucidaConsole;
++            fontFamily = 0x36;
++            table = kLucidaFontSizes;
++            tableSize = COUNT_OF(kLucidaFontSizes);
++            break;
++    }
++
++    size_t bestIndex = static_cast<size_t>(-1);
++    std::tuple<int, int> bestScore = std::make_tuple(-1, -1);
++
++    // We might want to pick the smallest possible font, because we don't know
++    // how large the monitor is (and the monitor size can change).  We might
++    // want to pick a larger font to accommodate console programs that resize
++    // the console on their own, like DOS edit.com, which tends to resize the
++    // console to 80 columns.
++
++    for (size_t i = 0; i < tableSize; ++i) {
++        const int width = table[i].width * columns;
++
++        // In general, we'd like to pick a font size where cutting the number
++        // of columns in half doesn't immediately violate the minimum width
++        // constraint.  (e.g. To run DOS edit.com, a user might resize their
++        // terminal to ~100 columns so it's big enough to show the 80 columns
++        // post-resize.)  To achieve this, give priority to fonts that allow
++        // this halving.  We don't want to encourage *very* large fonts,
++        // though, so disable the effect as the number of columns scales from
++        // 80 to 40.
++        const int halfColumns = std::min(columns, std::max(40, columns / 2));
++        const int halfWidth = table[i].width * halfColumns;
++
++        std::tuple<int, int> thisScore = std::make_tuple(-1, -1);
++        if (width >= 160 && halfWidth >= 160) {
++            // Both sizes are good.  Prefer the smaller fonts.
++            thisScore = std::make_tuple(2, -width);
++        } else if (width >= 160) {
++            // Prefer the smaller fonts.
++            thisScore = std::make_tuple(1, -width);
++        } else {
++            // Otherwise, prefer the largest font in our table.
++            thisScore = std::make_tuple(0, width);
++        }
++        if (thisScore > bestScore) {
++            bestIndex = i;
++            bestScore = thisScore;
++        }
++    }
++
++    ASSERT(bestIndex != static_cast<size_t>(-1));
++    return Font { faceName, fontFamily, table[bestIndex].size };
++}
++
++static void setSmallFontVista(VistaFontAPI &api, HANDLE conout,
++                              int columns, bool isNewW10) {
++    int codePage = GetConsoleOutputCP();
++    const auto font = selectSmallFont(codePage, columns, isNewW10);
++    if (setFontVista(api, conout, font)) {
++        trace("setSmallFontVista: success");
++        return;
++    }
++    if (codePage == 932 || codePage == 936 ||
++            codePage == 949 || codePage == 950) {
++        trace("setSmallFontVista: falling back to default codepage font instead");
++        const auto fontFB = selectSmallFont(0, columns, isNewW10);
++        if (setFontVista(api, conout, fontFB)) {
++            trace("setSmallFontVista: fallback was successful");
++            return;
++        }
++    }
++    trace("setSmallFontVista: failure");
++}
++
++struct FontSizeComparator {
++    bool operator()(const std::pair<DWORD, COORD> &obj1,
++                    const std::pair<DWORD, COORD> &obj2) const {
++        int score1 = obj1.second.X + obj1.second.Y;
++        int score2 = obj2.second.X + obj2.second.Y;
++        return score1 < score2;
++    }
++};
++
++static void setSmallFontXP(UndocumentedXPFontAPI &api, HANDLE conout) {
++    // Read the console font table and sort it from smallest to largest.
++    const DWORD fontCount = api.GetNumberOfConsoleFonts()();
++    trace("setSmallFontXP: number of console fonts: %u",
++        static_cast<unsigned>(fontCount));
++    std::vector<std::pair<DWORD, COORD> > table =
++        readFontTable(api, conout, fontCount);
++    std::sort(table.begin(), table.end(), FontSizeComparator());
++    for (size_t i = 0; i < table.size(); ++i) {
++        // Skip especially narrow fonts to permit narrower terminals.
++        if (table[i].second.X < 4) {
++            continue;
++        }
++        trace("setSmallFontXP: setting font to %u",
++            static_cast<unsigned>(table[i].first));
++        if (!api.SetConsoleFont()(conout, table[i].first)) {
++            trace("setSmallFontXP: SetConsoleFont call failed");
++            continue;
++        }
++        AGENT_CONSOLE_FONT_INFO info;
++        if (!api.GetCurrentConsoleFont()(conout, FALSE, &info)) {
++            trace("setSmallFontXP: GetCurrentConsoleFont call failed");
++            return;
++        }
++        if (info.nFont != table[i].first) {
++            trace("setSmallFontXP: font was not set");
++            dumpXPFont(api, conout, "setSmallFontXP: post-call font: ");
++            continue;
++        }
++        trace("setSmallFontXP: success");
++        return;
++    }
++    trace("setSmallFontXP: failure");
++}
++
++} // anonymous namespace
++
++// A Windows console window can never be larger than the desktop window.  To
++// maximize the possible size of the console in rows*cols, try to configure
++// the console with a small font.  Unfortunately, we cannot make the font *too*
++// small, because there is also a minimum window size in pixels.
++void setSmallFont(HANDLE conout, int columns, bool isNewW10) {
++    trace("setSmallFont: attempting to set a small font for %d columns "
++        "(CP=%u OutputCP=%u)",
++        columns,
++        static_cast<unsigned>(GetConsoleCP()),
++        static_cast<unsigned>(GetConsoleOutputCP()));
++    VistaFontAPI vista;
++    if (vista.valid()) {
++        dumpVistaFont(vista, conout, "previous font: ");
++        dumpFontTable(conout, "previous font table: ");
++        setSmallFontVista(vista, conout, columns, isNewW10);
++        dumpVistaFont(vista, conout, "new font: ");
++        dumpFontTable(conout, "new font table: ");
++        return;
++    }
++    UndocumentedXPFontAPI xp;
++    if (xp.valid()) {
++        dumpXPFont(xp, conout, "previous font: ");
++        dumpFontTable(conout, "previous font table: ");
++        setSmallFontXP(xp, conout);
++        dumpXPFont(xp, conout, "new font: ");
++        dumpFontTable(conout, "new font table: ");
++        return;
++    }
++    trace("setSmallFont: neither Vista nor XP APIs detected -- giving up");
++    dumpFontTable(conout, "font table: ");
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..99cb10698d9774696743684d676b02462169389d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,28 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef CONSOLEFONT_H
++#define CONSOLEFONT_H
++
++#include <windows.h>
++
++void setSmallFont(HANDLE conout, int columns, bool isNewW10);
++
++#endif // CONSOLEFONT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..192cac2a298f3325d56b52b94414caad4691c572
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,852 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "ConsoleInput.h"
++
++#include <stdio.h>
++#include <string.h>
++
++#include <algorithm>
++#include <string>
++
++#include "../include/winpty_constants.h"
++
++#include "../shared/DebugClient.h"
++#include "../shared/StringBuilder.h"
++#include "../shared/UnixCtrlChars.h"
++
++#include "ConsoleInputReencoding.h"
++#include "DebugShowInput.h"
++#include "DefaultInputMap.h"
++#include "DsrSender.h"
++#include "UnicodeEncoding.h"
++#include "Win32Console.h"
++
++// MAPVK_VK_TO_VSC isn't defined by the old MinGW.
++#ifndef MAPVK_VK_TO_VSC
++#define MAPVK_VK_TO_VSC 0
++#endif
++
++namespace {
++
++struct MouseRecord {
++    bool release;
++    int flags;
++    COORD coord;
++
++    std::string toString() const;
++};
++
++std::string MouseRecord::toString() const {
++    StringBuilder sb(40);
++    sb << "pos=" << coord.X << ',' << coord.Y
++       << " flags=0x" << hexOfInt(flags);
++    if (release) {
++        sb << " release";
++    }
++    return sb.str_moved();
++}
++
++const unsigned int kIncompleteEscapeTimeoutMs = 1000u;
++
++#define CHECK(cond)                                 \
++        do {                                        \
++            if (!(cond)) { return 0; }              \
++        } while(0)
++
++#define ADVANCE()                                   \
++        do {                                        \
++            pch++;                                  \
++            if (pch == stop) { return -1; }         \
++        } while(0)
++
++#define SCAN_INT(out, maxLen)                       \
++        do {                                        \
++            (out) = 0;                              \
++            CHECK(isdigit(*pch));                   \
++            const char *begin = pch;                \
++            do {                                    \
++                CHECK(pch - begin + 1 < maxLen);    \
++                (out) = (out) * 10 + *pch - '0';    \
++                ADVANCE();                          \
++            } while (isdigit(*pch));                \
++        } while(0)
++
++#define SCAN_SIGNED_INT(out, maxLen)                \
++        do {                                        \
++            bool negative = false;                  \
++            if (*pch == '-') {                      \
++                negative = true;                    \
++                ADVANCE();                          \
++            }                                       \
++            SCAN_INT(out, maxLen);                  \
++            if (negative) {                         \
++                (out) = -(out);                     \
++            }                                       \
++        } while(0)
++
++// Match the Device Status Report console input:  ESC [ nn ; mm R
++// Returns:
++// 0   no match
++// >0  match, returns length of match
++// -1  incomplete match
++static int matchDsr(const char *input, int inputSize)
++{
++    int32_t dummy = 0;
++    const char *pch = input;
++    const char *stop = input + inputSize;
++    CHECK(*pch == '\x1B');  ADVANCE();
++    CHECK(*pch == '[');     ADVANCE();
++    SCAN_INT(dummy, 8);
++    CHECK(*pch == ';');     ADVANCE();
++    SCAN_INT(dummy, 8);
++    CHECK(*pch == 'R');
++    return pch - input + 1;
++}
++
++static int matchMouseDefault(const char *input, int inputSize,
++                             MouseRecord &out)
++{
++    const char *pch = input;
++    const char *stop = input + inputSize;
++    CHECK(*pch == '\x1B');              ADVANCE();
++    CHECK(*pch == '[');                 ADVANCE();
++    CHECK(*pch == 'M');                 ADVANCE();
++    out.flags = (*pch - 32) & 0xFF;     ADVANCE();
++    out.coord.X = (*pch - '!') & 0xFF;
++    ADVANCE();
++    out.coord.Y = (*pch - '!') & 0xFF;
++    out.release = false;
++    return pch - input + 1;
++}
++
++static int matchMouse1006(const char *input, int inputSize, MouseRecord &out)
++{
++    const char *pch = input;
++    const char *stop = input + inputSize;
++    int32_t temp;
++    CHECK(*pch == '\x1B');      ADVANCE();
++    CHECK(*pch == '[');         ADVANCE();
++    CHECK(*pch == '<');         ADVANCE();
++    SCAN_INT(out.flags, 8);
++    CHECK(*pch == ';');         ADVANCE();
++    SCAN_SIGNED_INT(temp, 8); out.coord.X = temp - 1;
++    CHECK(*pch == ';');         ADVANCE();
++    SCAN_SIGNED_INT(temp, 8); out.coord.Y = temp - 1;
++    CHECK(*pch == 'M' || *pch == 'm');
++    out.release = (*pch == 'm');
++    return pch - input + 1;
++}
++
++static int matchMouse1015(const char *input, int inputSize, MouseRecord &out)
++{
++    const char *pch = input;
++    const char *stop = input + inputSize;
++    int32_t temp;
++    CHECK(*pch == '\x1B');      ADVANCE();
++    CHECK(*pch == '[');         ADVANCE();
++    SCAN_INT(out.flags, 8); out.flags -= 32;
++    CHECK(*pch == ';');         ADVANCE();
++    SCAN_SIGNED_INT(temp, 8); out.coord.X = temp - 1;
++    CHECK(*pch == ';');         ADVANCE();
++    SCAN_SIGNED_INT(temp, 8); out.coord.Y = temp - 1;
++    CHECK(*pch == 'M');
++    out.release = false;
++    return pch - input + 1;
++}
++
++// Match a mouse input escape sequence of any kind.
++// 0   no match
++// >0  match, returns length of match
++// -1  incomplete match
++static int matchMouseRecord(const char *input, int inputSize, MouseRecord &out)
++{
++    memset(&out, 0, sizeof(out));
++    int ret;
++    if ((ret = matchMouse1006(input, inputSize, out)) != 0) { return ret; }
++    if ((ret = matchMouse1015(input, inputSize, out)) != 0) { return ret; }
++    if ((ret = matchMouseDefault(input, inputSize, out)) != 0) { return ret; }
++    return 0;
++}
++
++#undef CHECK
++#undef ADVANCE
++#undef SCAN_INT
++
++} // anonymous namespace
++
++ConsoleInput::ConsoleInput(HANDLE conin, int mouseMode, DsrSender &dsrSender,
++                           Win32Console &console) :
++    m_console(console),
++    m_conin(conin),
++    m_mouseMode(mouseMode),
++    m_dsrSender(dsrSender)
++{
++    addDefaultEntriesToInputMap(m_inputMap);
++    if (hasDebugFlag("dump_input_map")) {
++        m_inputMap.dumpInputMap();
++    }
++
++    // Configure Quick Edit mode according to the mouse mode.  Enable
++    // InsertMode for two reasons:
++    //  - If it's OFF, it's difficult for the user to turn it ON.  The
++    //    properties dialog is inaccesible.  winpty still faithfully handles
++    //    the Insert key, which toggles between the insertion and overwrite
++    //    modes.
++    //  - When we modify the QuickEdit setting, if ExtendedFlags is OFF,
++    //    then we must choose the InsertMode setting.  I don't *think* this
++    //    case happens, though, because a new console always has ExtendedFlags
++    //    ON.
++    // See misc/EnableExtendedFlags.txt.
++    DWORD mode = 0;
++    if (!GetConsoleMode(conin, &mode)) {
++        trace("Agent startup: GetConsoleMode failed");
++    } else {
++        mode |= ENABLE_EXTENDED_FLAGS;
++        mode |= ENABLE_INSERT_MODE;
++        if (m_mouseMode == WINPTY_MOUSE_MODE_AUTO) {
++            mode |= ENABLE_QUICK_EDIT_MODE;
++        } else {
++            mode &= ~ENABLE_QUICK_EDIT_MODE;
++        }
++        if (!SetConsoleMode(conin, mode)) {
++            trace("Agent startup: SetConsoleMode failed");
++        }
++    }
++
++    updateInputFlags(true);
++}
++
++void ConsoleInput::writeInput(const std::string &input)
++{
++    if (input.size() == 0) {
++        return;
++    }
++
++    if (isTracingEnabled()) {
++        static bool debugInput = hasDebugFlag("input");
++        if (debugInput) {
++            std::string dumpString;
++            for (size_t i = 0; i < input.size(); ++i) {
++                const char ch = input[i];
++                const char ctrl = decodeUnixCtrlChar(ch);
++                if (ctrl != '\0') {
++                    dumpString += '^';
++                    dumpString += ctrl;
++                } else {
++                    dumpString += ch;
++                }
++            }
++            dumpString += " (";
++            for (size_t i = 0; i < input.size(); ++i) {
++                if (i > 0) {
++                    dumpString += ' ';
++                }
++                const unsigned char uch = input[i];
++                char buf[32];
++                winpty_snprintf(buf, "%02X", uch);
++                dumpString += buf;
++            }
++            dumpString += ')';
++            trace("input chars: %s", dumpString.c_str());
++        }
++    }
++
++    m_byteQueue.append(input);
++    doWrite(false);
++    if (!m_byteQueue.empty() && !m_dsrSent) {
++        trace("send DSR");
++        m_dsrSender.sendDsr();
++        m_dsrSent = true;
++    }
++    m_lastWriteTick = GetTickCount();
++}
++
++void ConsoleInput::flushIncompleteEscapeCode()
++{
++    if (!m_byteQueue.empty() &&
++            (GetTickCount() - m_lastWriteTick) > kIncompleteEscapeTimeoutMs) {
++        doWrite(true);
++        m_byteQueue.clear();
++    }
++}
++
++void ConsoleInput::updateInputFlags(bool forceTrace)
++{
++    const DWORD mode = inputConsoleMode();
++    const bool newFlagEE = (mode & ENABLE_EXTENDED_FLAGS) != 0;
++    const bool newFlagMI = (mode & ENABLE_MOUSE_INPUT) != 0;
++    const bool newFlagQE = (mode & ENABLE_QUICK_EDIT_MODE) != 0;
++    const bool newFlagEI = (mode & 0x200) != 0;
++    if (forceTrace ||
++            newFlagEE != m_enableExtendedEnabled ||
++            newFlagMI != m_mouseInputEnabled ||
++            newFlagQE != m_quickEditEnabled ||
++            newFlagEI != m_escapeInputEnabled) {
++        trace("CONIN modes: Extended=%s, MouseInput=%s QuickEdit=%s EscapeInput=%s",
++            newFlagEE ? "on" : "off",
++            newFlagMI ? "on" : "off",
++            newFlagQE ? "on" : "off",
++            newFlagEI ? "on" : "off");
++    }
++    m_enableExtendedEnabled = newFlagEE;
++    m_mouseInputEnabled = newFlagMI;
++    m_quickEditEnabled = newFlagQE;
++    m_escapeInputEnabled = newFlagEI;
++}
++
++bool ConsoleInput::shouldActivateTerminalMouse()
++{
++    // Return whether the agent should activate the terminal's mouse mode.
++    if (m_mouseMode == WINPTY_MOUSE_MODE_AUTO) {
++        // Some programs (e.g. Cygwin command-line programs like bash.exe and
++        // python2.7.exe) turn off ENABLE_EXTENDED_FLAGS and turn on
++        // ENABLE_MOUSE_INPUT, but do not turn off QuickEdit mode and do not
++        // actually care about mouse input.  Only enable the terminal mouse
++        // mode if ENABLE_EXTENDED_FLAGS is on.  See
++        // misc/EnableExtendedFlags.txt.
++        return m_mouseInputEnabled && !m_quickEditEnabled &&
++                m_enableExtendedEnabled;
++    } else if (m_mouseMode == WINPTY_MOUSE_MODE_FORCE) {
++        return true;
++    } else {
++        return false;
++    }
++}
++
++void ConsoleInput::doWrite(bool isEof)
++{
++    const char *data = m_byteQueue.c_str();
++    std::vector<INPUT_RECORD> records;
++    size_t idx = 0;
++    while (idx < m_byteQueue.size()) {
++        int charSize = scanInput(records, &data[idx], m_byteQueue.size() - idx, isEof);
++        if (charSize == -1)
++            break;
++        idx += charSize;
++    }
++    m_byteQueue.erase(0, idx);
++    flushInputRecords(records);
++}
++
++void ConsoleInput::flushInputRecords(std::vector<INPUT_RECORD> &records)
++{
++    if (records.size() == 0) {
++        return;
++    }
++    DWORD actual = 0;
++    if (!WriteConsoleInputW(m_conin, records.data(), records.size(), &actual)) {
++        trace("WriteConsoleInputW failed");
++    }
++    records.clear();
++}
++
++// This behavior isn't strictly correct, because the keypresses (probably?)
++// adopt the keyboard state (e.g. Ctrl/Alt/Shift modifiers) of the current
++// window station's keyboard, which has no necessary relationship to the winpty
++// instance.  It's unlikely to be an issue in practice, but it's conceivable.
++// (Imagine a foreground SSH server, where the local user holds down Ctrl,
++// while the remote user tries to use WSL navigation keys.)  I suspect using
++// the BackgroundDesktop mechanism in winpty would fix the problem.
++//
++// https://github.com/rprichard/winpty/issues/116
++static void sendKeyMessage(HWND hwnd, bool isKeyDown, uint16_t virtualKey)
++{
++    uint32_t scanCode = MapVirtualKey(virtualKey, MAPVK_VK_TO_VSC);
++    if (scanCode > 255) {
++        scanCode = 0;
++    }
++    SendMessage(hwnd, isKeyDown ? WM_KEYDOWN : WM_KEYUP, virtualKey,
++        (scanCode << 16) | 1u | (isKeyDown ? 0u : 0xc0000000u));
++}
++
++int ConsoleInput::scanInput(std::vector<INPUT_RECORD> &records,
++                            const char *input,
++                            int inputSize,
++                            bool isEof)
++{
++    ASSERT(inputSize >= 1);
++
++    // Ctrl-C.
++    //
++    // In processed mode, use GenerateConsoleCtrlEvent so that Ctrl-C handlers
++    // are called.  GenerateConsoleCtrlEvent unfortunately doesn't interrupt
++    // ReadConsole calls[1].  Using WM_KEYDOWN/UP fixes the ReadConsole
++    // problem, but breaks in background window stations/desktops.
++    //
++    // In unprocessed mode, there's an entry for Ctrl-C in the SimpleEncoding
++    // table in DefaultInputMap.
++    //
++    // [1] https://github.com/rprichard/winpty/issues/116
++    if (input[0] == '\x03' && (inputConsoleMode() & ENABLE_PROCESSED_INPUT)) {
++        flushInputRecords(records);
++        trace("Ctrl-C");
++        const BOOL ret = GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
++        trace("GenerateConsoleCtrlEvent: %d", ret);
++        return 1;
++    }
++
++    if (input[0] == '\x1B') {
++        // Attempt to match the Device Status Report (DSR) reply.
++        int dsrLen = matchDsr(input, inputSize);
++        if (dsrLen > 0) {
++            trace("Received a DSR reply");
++            m_dsrSent = false;
++            return dsrLen;
++        } else if (!isEof && dsrLen == -1) {
++            // Incomplete DSR match.
++            trace("Incomplete DSR match");
++            return -1;
++        }
++
++        int mouseLen = scanMouseInput(records, input, inputSize);
++        if (mouseLen > 0 || (!isEof && mouseLen == -1)) {
++            return mouseLen;
++        }
++    }
++
++    // Search the input map.
++    InputMap::Key match;
++    bool incomplete;
++    int matchLen = m_inputMap.lookupKey(input, inputSize, match, incomplete);
++    if (!isEof && incomplete) {
++        // Incomplete match -- need more characters (or wait for a
++        // timeout to signify flushed input).
++        trace("Incomplete escape sequence");
++        return -1;
++    } else if (matchLen > 0) {
++        uint32_t winCodePointDn = match.unicodeChar;
++        if ((match.keyState & LEFT_CTRL_PRESSED) && (match.keyState & LEFT_ALT_PRESSED)) {
++            winCodePointDn = '\0';
++        }
++        uint32_t winCodePointUp = winCodePointDn;
++        if (match.keyState & LEFT_ALT_PRESSED) {
++            winCodePointUp = '\0';
++        }
++        appendKeyPress(records, match.virtualKey,
++                       winCodePointDn, winCodePointUp, match.keyState,
++                       match.unicodeChar, match.keyState);
++        return matchLen;
++    }
++
++    // Recognize Alt-<character>.
++    //
++    // This code doesn't match Alt-ESC, which is encoded as `ESC ESC`, but
++    // maybe it should.  I was concerned that pressing ESC rapidly enough could
++    // accidentally trigger Alt-ESC.  (e.g. The user would have to be faster
++    // than the DSR flushing mechanism or use a decrepit terminal.  The user
++    // might be on a slow network connection.)
++    if (input[0] == '\x1B' && inputSize >= 2 && input[1] != '\x1B') {
++        const int len = utf8CharLength(input[1]);
++        if (len > 0) {
++            if (1 + len > inputSize) {
++                // Incomplete character.
++                trace("Incomplete UTF-8 character in Alt-<Char>");
++                return -1;
++            }
++            appendUtf8Char(records, &input[1], len, true);
++            return 1 + len;
++        }
++    }
++
++    // A UTF-8 character.
++    const int len = utf8CharLength(input[0]);
++    if (len == 0) {
++        static bool debugInput = isTracingEnabled() && hasDebugFlag("input");
++        if (debugInput) {
++            trace("Discarding invalid input byte: %02X",
++                static_cast<unsigned char>(input[0]));
++        }
++        return 1;
++    }
++    if (len > inputSize) {
++        // Incomplete character.
++        trace("Incomplete UTF-8 character");
++        return -1;
++    }
++    appendUtf8Char(records, &input[0], len, false);
++    return len;
++}
++
++int ConsoleInput::scanMouseInput(std::vector<INPUT_RECORD> &records,
++                                 const char *input,
++                                 int inputSize)
++{
++    MouseRecord record;
++    const int len = matchMouseRecord(input, inputSize, record);
++    if (len <= 0) {
++        return len;
++    }
++
++    if (isTracingEnabled()) {
++        static bool debugInput = hasDebugFlag("input");
++        if (debugInput) {
++            trace("mouse input: %s", record.toString().c_str());
++        }
++    }
++
++    const int button = record.flags & 0x03;
++    INPUT_RECORD newRecord = {0};
++    newRecord.EventType = MOUSE_EVENT;
++    MOUSE_EVENT_RECORD &mer = newRecord.Event.MouseEvent;
++
++    mer.dwMousePosition.X =
++        m_mouseWindowRect.Left +
++            std::max(0, std::min<int>(record.coord.X,
++                                      m_mouseWindowRect.width() - 1));
++
++    mer.dwMousePosition.Y =
++        m_mouseWindowRect.Top +
++            std::max(0, std::min<int>(record.coord.Y,
++                                      m_mouseWindowRect.height() - 1));
++
++    // The modifier state is neatly independent of everything else.
++    if (record.flags & 0x04) { mer.dwControlKeyState |= SHIFT_PRESSED;     }
++    if (record.flags & 0x08) { mer.dwControlKeyState |= LEFT_ALT_PRESSED;  }
++    if (record.flags & 0x10) { mer.dwControlKeyState |= LEFT_CTRL_PRESSED; }
++
++    if (record.flags & 0x40) {
++        // Mouse wheel
++        mer.dwEventFlags |= MOUSE_WHEELED;
++        if (button == 0) {
++            // up
++            mer.dwButtonState |= 0x00780000;
++        } else if (button == 1) {
++            // down
++            mer.dwButtonState |= 0xff880000;
++        } else {
++            // Invalid -- do nothing
++            return len;
++        }
++    } else {
++        // Ordinary mouse event
++        if (record.flags & 0x20) { mer.dwEventFlags |= MOUSE_MOVED; }
++        if (button == 3) {
++            m_mouseButtonState = 0;
++            // Potentially advance double-click detection.
++            m_doubleClick.released = true;
++        } else {
++            const DWORD relevantFlag =
++                (button == 0) ? FROM_LEFT_1ST_BUTTON_PRESSED :
++                (button == 1) ? FROM_LEFT_2ND_BUTTON_PRESSED :
++                (button == 2) ? RIGHTMOST_BUTTON_PRESSED :
++                0;
++            ASSERT(relevantFlag != 0);
++            if (record.release) {
++                m_mouseButtonState &= ~relevantFlag;
++                if (relevantFlag == m_doubleClick.button) {
++                    // Potentially advance double-click detection.
++                    m_doubleClick.released = true;
++                } else {
++                    // End double-click detection.
++                    m_doubleClick = DoubleClickDetection();
++                }
++            } else if ((m_mouseButtonState & relevantFlag) == 0) {
++                // The button has been newly pressed.
++                m_mouseButtonState |= relevantFlag;
++                // Detect a double-click.  This code looks for an exact
++                // coordinate match, which is stricter than what Windows does,
++                // but Windows has pixel coordinates, and we only have terminal
++                // coordinates.
++                if (m_doubleClick.button == relevantFlag &&
++                        m_doubleClick.pos == record.coord &&
++                        (GetTickCount() - m_doubleClick.tick <
++                            GetDoubleClickTime())) {
++                    // Record a double-click and end double-click detection.
++                    mer.dwEventFlags |= DOUBLE_CLICK;
++                    m_doubleClick = DoubleClickDetection();
++                } else {
++                    // Begin double-click detection.
++                    m_doubleClick.button = relevantFlag;
++                    m_doubleClick.pos = record.coord;
++                    m_doubleClick.tick = GetTickCount();
++                }
++            }
++        }
++    }
++
++    mer.dwButtonState |= m_mouseButtonState;
++
++    if (m_mouseInputEnabled && !m_quickEditEnabled) {
++        if (isTracingEnabled()) {
++            static bool debugInput = hasDebugFlag("input");
++            if (debugInput) {
++                trace("mouse event: %s", mouseEventToString(mer).c_str());
++            }
++        }
++
++        records.push_back(newRecord);
++    }
++
++    return len;
++}
++
++void ConsoleInput::appendUtf8Char(std::vector<INPUT_RECORD> &records,
++                                  const char *charBuffer,
++                                  const int charLen,
++                                  const bool terminalAltEscape)
++{
++    const uint32_t codePoint = decodeUtf8(charBuffer);
++    if (codePoint == static_cast<uint32_t>(-1)) {
++        static bool debugInput = isTracingEnabled() && hasDebugFlag("input");
++        if (debugInput) {
++            StringBuilder error(64);
++            error << "Discarding invalid UTF-8 sequence:";
++            for (int i = 0; i < charLen; ++i) {
++                error << ' ';
++                error << hexOfInt<true, uint8_t>(charBuffer[i]);
++            }
++            trace("%s", error.c_str());
++        }
++        return;
++    }
++
++    const short charScan = codePoint > 0xFFFF ? -1 : VkKeyScan(codePoint);
++    uint16_t virtualKey = 0;
++    uint16_t winKeyState = 0;
++    uint32_t winCodePointDn = codePoint;
++    uint32_t winCodePointUp = codePoint;
++    uint16_t vtKeyState = 0;
++
++    if (charScan != -1) {
++        virtualKey = charScan & 0xFF;
++        if (charScan & 0x100) {
++            winKeyState |= SHIFT_PRESSED;
++        }
++        if (charScan & 0x200) {
++            winKeyState |= LEFT_CTRL_PRESSED;
++        }
++        if (charScan & 0x400) {
++            winKeyState |= RIGHT_ALT_PRESSED;
++        }
++        if (terminalAltEscape && (winKeyState & LEFT_CTRL_PRESSED)) {
++            // If the terminal escapes a Ctrl-<Key> with Alt, then set the
++            // codepoint to 0.  On the other hand, if a character requires
++            // AltGr (like U+00B2 on a German layout), then VkKeyScan will
++            // report both Ctrl and Alt pressed, and we should keep the
++            // codepoint.  See https://github.com/rprichard/winpty/issues/109.
++            winCodePointDn = 0;
++            winCodePointUp = 0;
++        }
++    }
++    if (terminalAltEscape) {
++        winCodePointUp = 0;
++        winKeyState |= LEFT_ALT_PRESSED;
++        vtKeyState |= LEFT_ALT_PRESSED;
++    }
++
++    appendKeyPress(records, virtualKey,
++                   winCodePointDn, winCodePointUp, winKeyState,
++                   codePoint, vtKeyState);
++}
++
++void ConsoleInput::appendKeyPress(std::vector<INPUT_RECORD> &records,
++                                  const uint16_t virtualKey,
++                                  const uint32_t winCodePointDn,
++                                  const uint32_t winCodePointUp,
++                                  const uint16_t winKeyState,
++                                  const uint32_t vtCodePoint,
++                                  const uint16_t vtKeyState)
++{
++    const bool ctrl = (winKeyState & LEFT_CTRL_PRESSED) != 0;
++    const bool leftAlt = (winKeyState & LEFT_ALT_PRESSED) != 0;
++    const bool rightAlt = (winKeyState & RIGHT_ALT_PRESSED) != 0;
++    const bool shift = (winKeyState & SHIFT_PRESSED) != 0;
++    const bool enhanced = (winKeyState & ENHANCED_KEY) != 0;
++    bool hasDebugInput = false;
++
++    if (isTracingEnabled()) {
++        static bool debugInput = hasDebugFlag("input");
++        if (debugInput) {
++            hasDebugInput = true;
++            InputMap::Key key = { virtualKey, winCodePointDn, winKeyState };
++            trace("keypress: %s", key.toString().c_str());
++        }
++    }
++
++    if (m_escapeInputEnabled &&
++            (virtualKey == VK_UP ||
++                virtualKey == VK_DOWN ||
++                virtualKey == VK_LEFT ||
++                virtualKey == VK_RIGHT ||
++                virtualKey == VK_HOME ||
++                virtualKey == VK_END) &&
++            !ctrl && !leftAlt && !rightAlt && !shift) {
++        flushInputRecords(records);
++        if (hasDebugInput) {
++            trace("sending keypress to console HWND");
++        }
++        sendKeyMessage(m_console.hwnd(), true, virtualKey);
++        sendKeyMessage(m_console.hwnd(), false, virtualKey);
++        return;
++    }
++
++    uint16_t stepKeyState = 0;
++    if (ctrl) {
++        stepKeyState |= LEFT_CTRL_PRESSED;
++        appendInputRecord(records, TRUE, VK_CONTROL, 0, stepKeyState);
++    }
++    if (leftAlt) {
++        stepKeyState |= LEFT_ALT_PRESSED;
++        appendInputRecord(records, TRUE, VK_MENU, 0, stepKeyState);
++    }
++    if (rightAlt) {
++        stepKeyState |= RIGHT_ALT_PRESSED;
++        appendInputRecord(records, TRUE, VK_MENU, 0, stepKeyState | ENHANCED_KEY);
++    }
++    if (shift) {
++        stepKeyState |= SHIFT_PRESSED;
++        appendInputRecord(records, TRUE, VK_SHIFT, 0, stepKeyState);
++    }
++    if (enhanced) {
++        stepKeyState |= ENHANCED_KEY;
++    }
++    if (m_escapeInputEnabled) {
++        reencodeEscapedKeyPress(records, virtualKey, vtCodePoint, vtKeyState);
++    } else {
++        appendCPInputRecords(records, TRUE, virtualKey, winCodePointDn, stepKeyState);
++    }
++    appendCPInputRecords(records, FALSE, virtualKey, winCodePointUp, stepKeyState);
++    if (enhanced) {
++        stepKeyState &= ~ENHANCED_KEY;
++    }
++    if (shift) {
++        stepKeyState &= ~SHIFT_PRESSED;
++        appendInputRecord(records, FALSE, VK_SHIFT, 0, stepKeyState);
++    }
++    if (rightAlt) {
++        stepKeyState &= ~RIGHT_ALT_PRESSED;
++        appendInputRecord(records, FALSE, VK_MENU, 0, stepKeyState | ENHANCED_KEY);
++    }
++    if (leftAlt) {
++        stepKeyState &= ~LEFT_ALT_PRESSED;
++        appendInputRecord(records, FALSE, VK_MENU, 0, stepKeyState);
++    }
++    if (ctrl) {
++        stepKeyState &= ~LEFT_CTRL_PRESSED;
++        appendInputRecord(records, FALSE, VK_CONTROL, 0, stepKeyState);
++    }
++}
++
++void ConsoleInput::appendCPInputRecords(std::vector<INPUT_RECORD> &records,
++                                        BOOL keyDown,
++                                        uint16_t virtualKey,
++                                        uint32_t codePoint,
++                                        uint16_t keyState)
++{
++    // This behavior really doesn't match that of the Windows console (in
++    // normal, non-escape-mode).  Judging by the copy-and-paste behavior,
++    // Windows apparently handles everything outside of the keyboard layout by
++    // first sending a sequence of Alt+KeyPad events, then finally a key-up
++    // event whose UnicodeChar has the appropriate value.  For U+00A2 (CENT
++    // SIGN):
++    //
++    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
++    //      key: dn rpt=1 scn=79 LAlt-NUMPAD1 ch=0
++    //      key: up rpt=1 scn=79 LAlt-NUMPAD1 ch=0
++    //      key: dn rpt=1 scn=76 LAlt-NUMPAD5 ch=0
++    //      key: up rpt=1 scn=76 LAlt-NUMPAD5 ch=0
++    //      key: dn rpt=1 scn=76 LAlt-NUMPAD5 ch=0
++    //      key: up rpt=1 scn=76 LAlt-NUMPAD5 ch=0
++    //      key: up rpt=1 scn=56 MENU ch=0xa2
++    //
++    // The Alt+155 value matches the encoding of U+00A2 in CP-437.  Curiously,
++    // if I use "chcp 1252" to change the encoding, then copy-and-pasting
++    // produces Alt+162 instead.  (U+00A2 is 162 in CP-1252.)  However, typing
++    // Alt+155 or Alt+162 produce the same characters regardless of console
++    // code page.  (That is, they use CP-437 and yield U+00A2 and U+00F3.)
++    //
++    // For characters outside the BMP, Windows repeats the process for both
++    // UTF-16 code units, e.g, for U+1F300 (CYCLONE):
++    //
++    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
++    //      key: dn rpt=1 scn=77 LAlt-NUMPAD6 ch=0
++    //      key: up rpt=1 scn=77 LAlt-NUMPAD6 ch=0
++    //      key: dn rpt=1 scn=81 LAlt-NUMPAD3 ch=0
++    //      key: up rpt=1 scn=81 LAlt-NUMPAD3 ch=0
++    //      key: up rpt=1 scn=56 MENU ch=0xd83c
++    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
++    //      key: dn rpt=1 scn=77 LAlt-NUMPAD6 ch=0
++    //      key: up rpt=1 scn=77 LAlt-NUMPAD6 ch=0
++    //      key: dn rpt=1 scn=81 LAlt-NUMPAD3 ch=0
++    //      key: up rpt=1 scn=81 LAlt-NUMPAD3 ch=0
++    //      key: up rpt=1 scn=56 MENU ch=0xdf00
++    //
++    // In this case, it sends Alt+63 twice, which signifies '?'.  Apparently
++    // CMD and Cygwin bash are both able to decode this.
++    //
++    // Also note that typing Alt+NNN still works if NumLock is off, e.g.:
++    //
++    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
++    //      key: dn rpt=1 scn=79 LAlt-END ch=0
++    //      key: up rpt=1 scn=79 LAlt-END ch=0
++    //      key: dn rpt=1 scn=76 LAlt-CLEAR ch=0
++    //      key: up rpt=1 scn=76 LAlt-CLEAR ch=0
++    //      key: dn rpt=1 scn=76 LAlt-CLEAR ch=0
++    //      key: up rpt=1 scn=76 LAlt-CLEAR ch=0
++    //      key: up rpt=1 scn=56 MENU ch=0xa2
++    //
++    // Evidently, the Alt+NNN key events are not intended to be decoded to a
++    // character.  Maybe programs are looking for a key-up ALT/MENU event with
++    // a non-zero character?
++
++    wchar_t ws[2];
++    const int wslen = encodeUtf16(ws, codePoint);
++
++    if (wslen == 1) {
++        appendInputRecord(records, keyDown, virtualKey, ws[0], keyState);
++    } else if (wslen == 2) {
++        appendInputRecord(records, keyDown, virtualKey, ws[0], keyState);
++        appendInputRecord(records, keyDown, virtualKey, ws[1], keyState);
++    } else {
++        // This situation isn't that bad, but it should never happen,
++        // because invalid codepoints shouldn't reach this point.
++        trace("INTERNAL ERROR: appendInputRecordCP: invalid codePoint: "
++              "U+%04X", codePoint);
++    }
++}
++
++void ConsoleInput::appendInputRecord(std::vector<INPUT_RECORD> &records,
++                                     BOOL keyDown,
++                                     uint16_t virtualKey,
++                                     wchar_t utf16Char,
++                                     uint16_t keyState)
++{
++    INPUT_RECORD ir = {};
++    ir.EventType = KEY_EVENT;
++    ir.Event.KeyEvent.bKeyDown = keyDown;
++    ir.Event.KeyEvent.wRepeatCount = 1;
++    ir.Event.KeyEvent.wVirtualKeyCode = virtualKey;
++    ir.Event.KeyEvent.wVirtualScanCode =
++            MapVirtualKey(virtualKey, MAPVK_VK_TO_VSC);
++    ir.Event.KeyEvent.uChar.UnicodeChar = utf16Char;
++    ir.Event.KeyEvent.dwControlKeyState = keyState;
++    records.push_back(ir);
++}
++
++DWORD ConsoleInput::inputConsoleMode()
++{
++    DWORD mode = 0;
++    if (!GetConsoleMode(m_conin, &mode)) {
++        trace("GetConsoleMode failed");
++        return 0;
++    }
++    return mode;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e807d973ba541f322fad48f6cf3c6dbb555f10ca
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,109 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef CONSOLEINPUT_H
++#define CONSOLEINPUT_H
++
++#include <windows.h>
++#include <stdint.h>
++
++#include <memory>
++#include <string>
++#include <vector>
++
++#include "Coord.h"
++#include "InputMap.h"
++#include "SmallRect.h"
++
++class Win32Console;
++class DsrSender;
++
++class ConsoleInput
++{
++public:
++    ConsoleInput(HANDLE conin, int mouseMode, DsrSender &dsrSender,
++                 Win32Console &console);
++    void writeInput(const std::string &input);
++    void flushIncompleteEscapeCode();
++    void setMouseWindowRect(SmallRect val) { m_mouseWindowRect = val; }
++    void updateInputFlags(bool forceTrace=false);
++    bool shouldActivateTerminalMouse();
++
++private:
++    void doWrite(bool isEof);
++    void flushInputRecords(std::vector<INPUT_RECORD> &records);
++    int scanInput(std::vector<INPUT_RECORD> &records,
++                  const char *input,
++                  int inputSize,
++                  bool isEof);
++    int scanMouseInput(std::vector<INPUT_RECORD> &records,
++                       const char *input,
++                       int inputSize);
++    void appendUtf8Char(std::vector<INPUT_RECORD> &records,
++                        const char *charBuffer,
++                        int charLen,
++                        bool terminalAltEscape);
++    void appendKeyPress(std::vector<INPUT_RECORD> &records,
++                        uint16_t virtualKey,
++                        uint32_t winCodePointDn,
++                        uint32_t winCodePointUp,
++                        uint16_t winKeyState,
++                        uint32_t vtCodePoint,
++                        uint16_t vtKeyState);
++
++public:
++    static void appendCPInputRecords(std::vector<INPUT_RECORD> &records,
++                                     BOOL keyDown,
++                                     uint16_t virtualKey,
++                                     uint32_t codePoint,
++                                     uint16_t keyState);
++    static void appendInputRecord(std::vector<INPUT_RECORD> &records,
++                                  BOOL keyDown,
++                                  uint16_t virtualKey,
++                                  wchar_t utf16Char,
++                                  uint16_t keyState);
++
++private:
++    DWORD inputConsoleMode();
++
++private:
++    Win32Console &m_console;
++    HANDLE m_conin = nullptr;
++    int m_mouseMode = 0;
++    DsrSender &m_dsrSender;
++    bool m_dsrSent = false;
++    std::string m_byteQueue;
++    InputMap m_inputMap;
++    DWORD m_lastWriteTick = 0;
++    DWORD m_mouseButtonState = 0;
++    struct DoubleClickDetection {
++        DWORD button = 0;
++        Coord pos;
++        DWORD tick = 0;
++        bool released = false;
++    } m_doubleClick;
++    bool m_enableExtendedEnabled = false;
++    bool m_mouseInputEnabled = false;
++    bool m_quickEditEnabled = false;
++    bool m_escapeInputEnabled = false;
++    SmallRect m_mouseWindowRect;
++};
++
++#endif // CONSOLEINPUT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b79545eea9cf7de668a668d5b2f6e186bcaa2d2c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,121 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "ConsoleInputReencoding.h"
++
++#include "ConsoleInput.h"
++
++namespace {
++
++static void outch(std::vector<INPUT_RECORD> &out, wchar_t ch) {
++    ConsoleInput::appendInputRecord(out, TRUE, 0, ch, 0);
++}
++
++} // anonymous namespace
++
++void reencodeEscapedKeyPress(
++        std::vector<INPUT_RECORD> &out,
++        uint16_t virtualKey,
++        uint32_t codePoint,
++        uint16_t keyState) {
++
++    struct EscapedKey {
++        enum { None, Numeric, Letter } kind;
++        wchar_t content[2];
++    };
++
++    EscapedKey escapeCode = {};
++    switch (virtualKey) {
++        case VK_UP:     escapeCode = { EscapedKey::Letter, {'A'} }; break;
++        case VK_DOWN:   escapeCode = { EscapedKey::Letter, {'B'} }; break;
++        case VK_RIGHT:  escapeCode = { EscapedKey::Letter, {'C'} }; break;
++        case VK_LEFT:   escapeCode = { EscapedKey::Letter, {'D'} }; break;
++        case VK_CLEAR:  escapeCode = { EscapedKey::Letter, {'E'} }; break;
++        case VK_F1:     escapeCode = { EscapedKey::Numeric, {'1', '1'} }; break;
++        case VK_F2:     escapeCode = { EscapedKey::Numeric, {'1', '2'} }; break;
++        case VK_F3:     escapeCode = { EscapedKey::Numeric, {'1', '3'} }; break;
++        case VK_F4:     escapeCode = { EscapedKey::Numeric, {'1', '4'} }; break;
++        case VK_F5:     escapeCode = { EscapedKey::Numeric, {'1', '5'} }; break;
++        case VK_F6:     escapeCode = { EscapedKey::Numeric, {'1', '7'} }; break;
++        case VK_F7:     escapeCode = { EscapedKey::Numeric, {'1', '8'} }; break;
++        case VK_F8:     escapeCode = { EscapedKey::Numeric, {'1', '9'} }; break;
++        case VK_F9:     escapeCode = { EscapedKey::Numeric, {'2', '0'} }; break;
++        case VK_F10:    escapeCode = { EscapedKey::Numeric, {'2', '1'} }; break;
++        case VK_F11:    escapeCode = { EscapedKey::Numeric, {'2', '3'} }; break;
++        case VK_F12:    escapeCode = { EscapedKey::Numeric, {'2', '4'} }; break;
++        case VK_HOME:   escapeCode = { EscapedKey::Letter, {'H'} }; break;
++        case VK_INSERT: escapeCode = { EscapedKey::Numeric, {'2'} }; break;
++        case VK_DELETE: escapeCode = { EscapedKey::Numeric, {'3'} }; break;
++        case VK_END:    escapeCode = { EscapedKey::Letter, {'F'} }; break;
++        case VK_PRIOR:  escapeCode = { EscapedKey::Numeric, {'5'} }; break;
++        case VK_NEXT:   escapeCode = { EscapedKey::Numeric, {'6'} }; break;
++    }
++    if (escapeCode.kind != EscapedKey::None) {
++        int flags = 0;
++        if (keyState & SHIFT_PRESSED)       { flags |= 0x1; }
++        if (keyState & LEFT_ALT_PRESSED)    { flags |= 0x2; }
++        if (keyState & LEFT_CTRL_PRESSED)   { flags |= 0x4; }
++        outch(out, L'\x1b');
++        outch(out, L'[');
++        if (escapeCode.kind == EscapedKey::Numeric) {
++            for (wchar_t ch : escapeCode.content) {
++                if (ch != L'\0') {
++                    outch(out, ch);
++                }
++            }
++        } else if (flags != 0) {
++            outch(out, L'1');
++        }
++        if (flags != 0) {
++            outch(out, L';');
++            outch(out, L'1' + flags);
++        }
++        if (escapeCode.kind == EscapedKey::Numeric) {
++            outch(out, L'~');
++        } else {
++            outch(out, escapeCode.content[0]);
++        }
++        return;
++    }
++
++    switch (virtualKey) {
++        case VK_BACK:
++            if (keyState & LEFT_ALT_PRESSED) {
++                outch(out, L'\x1b');
++            }
++            outch(out, L'\x7f');
++            return;
++        case VK_TAB:
++            if (keyState & SHIFT_PRESSED) {
++                outch(out, L'\x1b');
++                outch(out, L'[');
++                outch(out, L'Z');
++                return;
++            }
++            break;
++    }
++
++    if (codePoint != 0) {
++        if (keyState & LEFT_ALT_PRESSED) {
++            outch(out, L'\x1b');
++        }
++        ConsoleInput::appendCPInputRecords(out, TRUE, 0, codePoint, 0);
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..63bc006b5a7ce96e610cf3ca144e4a636dae85ce
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,36 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_CONSOLE_INPUT_REENCODING_H
++#define AGENT_CONSOLE_INPUT_REENCODING_H
++
++#include <windows.h>
++
++#include <stdint.h>
++
++#include <vector>
++
++void reencodeEscapedKeyPress(
++    std::vector<INPUT_RECORD> &records,
++    uint16_t virtualKey,
++    uint32_t codePoint,
++    uint16_t keyState);
++
++#endif // AGENT_CONSOLE_INPUT_REENCODING_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1d2bcb76859a51c60726b12d7f2eac2597cb944c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,152 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++//
++// ConsoleLine
++//
++// This data structure keep tracks of the previous CHAR_INFO content of an
++// output line and determines when a line has changed.  Detecting line changes
++// is made complicated by terminal resizing.
++//
++
++#include "ConsoleLine.h"
++
++#include <algorithm>
++
++#include "../shared/WinptyAssert.h"
++
++static CHAR_INFO blankChar(WORD attributes)
++{
++    // N.B.: As long as we write to UnicodeChar rather than AsciiChar, there
++    // are no padding bytes that could contain uninitialized bytes.  This fact
++    // is important for efficient comparison.
++    CHAR_INFO ret;
++    ret.Attributes = attributes;
++    ret.Char.UnicodeChar = L' ';
++    return ret;
++}
++
++static bool isLineBlank(const CHAR_INFO *line, int length, WORD attributes)
++{
++    for (int col = 0; col < length; ++col) {
++        if (line[col].Attributes != attributes ||
++                line[col].Char.UnicodeChar != L' ') {
++            return false;
++        }
++    }
++    return true;
++}
++
++static inline bool areLinesEqual(
++    const CHAR_INFO *line1,
++    const CHAR_INFO *line2,
++    int length)
++{
++    return memcmp(line1, line2, sizeof(CHAR_INFO) * length) == 0;
++}
++
++ConsoleLine::ConsoleLine() : m_prevLength(0)
++{
++}
++
++void ConsoleLine::reset()
++{
++    m_prevLength = 0;
++    m_prevData.clear();
++}
++
++// Determines whether the given line is sufficiently different from the
++// previously seen line as to justify reoutputting the line.  The function
++// also sets the `ConsoleLine` to the given line, exactly as if `setLine` had
++// been called.
++bool ConsoleLine::detectChangeAndSetLine(const CHAR_INFO *const line, const int newLength)
++{
++    ASSERT(newLength >= 1);
++    ASSERT(m_prevLength <= static_cast<int>(m_prevData.size()));
++
++    if (newLength == m_prevLength) {
++        bool equalLines = areLinesEqual(m_prevData.data(), line, newLength);
++        if (!equalLines) {
++            setLine(line, newLength);
++        }
++        return !equalLines;
++    } else {
++        if (m_prevLength == 0) {
++            setLine(line, newLength);
++            return true;
++        }
++
++        ASSERT(m_prevLength >= 1);
++        const WORD prevBlank = m_prevData[m_prevLength - 1].Attributes;
++        const WORD newBlank = line[newLength - 1].Attributes;
++
++        bool equalLines = false;
++        if (newLength < m_prevLength) {
++            // The line has become shorter.  The lines are equal if the common
++            // part is equal, and if the newly truncated characters were blank.
++            equalLines =
++                areLinesEqual(m_prevData.data(), line, newLength) &&
++                isLineBlank(m_prevData.data() + newLength,
++                            m_prevLength - newLength,
++                            newBlank);
++        } else {
++            //
++            // The line has become longer.  The lines are equal if the common
++            // part is equal, and if both the extra characters and any
++            // potentially reexposed characters are blank.
++            //
++            // Two of the most relevant terminals for winpty--mintty and
++            // jediterm--don't (currently) erase the obscured content when a
++            // line is cleared, so we should anticipate its existence when
++            // making a terminal wider and reoutput the line.  See:
++            //
++            //  * https://github.com/mintty/mintty/issues/480
++            //  * https://github.com/JetBrains/jediterm/issues/118
++            //
++            ASSERT(newLength > m_prevLength);
++            equalLines =
++                areLinesEqual(m_prevData.data(), line, m_prevLength) &&
++                isLineBlank(m_prevData.data() + m_prevLength,
++                            std::min<int>(m_prevData.size(), newLength) - m_prevLength,
++                            prevBlank) &&
++                isLineBlank(line + m_prevLength,
++                            newLength - m_prevLength,
++                            prevBlank);
++        }
++        setLine(line, newLength);
++        return !equalLines;
++    }
++}
++
++void ConsoleLine::setLine(const CHAR_INFO *const line, const int newLength)
++{
++    if (static_cast<int>(m_prevData.size()) < newLength) {
++        m_prevData.resize(newLength);
++    }
++    memcpy(m_prevData.data(), line, sizeof(CHAR_INFO) * newLength);
++    m_prevLength = newLength;
++}
++
++void ConsoleLine::blank(WORD attributes)
++{
++    m_prevData.resize(1);
++    m_prevData[0] = blankChar(attributes);
++    m_prevLength = 1;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..802c189c7566a992cbc1c4b8d1d8406d83023252
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,41 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef CONSOLE_LINE_H
++#define CONSOLE_LINE_H
++
++#include <windows.h>
++
++#include <vector>
++
++class ConsoleLine
++{
++public:
++    ConsoleLine();
++    void reset();
++    bool detectChangeAndSetLine(const CHAR_INFO *line, int newLength);
++    void setLine(const CHAR_INFO *line, int newLength);
++    void blank(WORD attributes);
++private:
++    int m_prevLength;
++    std::vector<CHAR_INFO> m_prevData;
++};
++
++#endif // CONSOLE_LINE_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..74c98addac696baa3e32da3846f61cf29bd5c4a5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,87 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef COORD_H
++#define COORD_H
++
++#include <windows.h>
++
++#include <string>
++
++#include "../shared/winpty_snprintf.h"
++
++struct Coord : COORD {
++    Coord()
++    {
++        X = 0;
++        Y = 0;
++    }
++
++    Coord(SHORT x, SHORT y)
++    {
++        X = x;
++        Y = y;
++    }
++
++    Coord(COORD other)
++    {
++        *(COORD*)this = other;
++    }
++
++    Coord(const Coord &other)
++    {
++        *(COORD*)this = *(const COORD*)&other;
++    }
++
++    Coord &operator=(const Coord &other)
++    {
++        *(COORD*)this = *(const COORD*)&other;
++        return *this;
++    }
++
++    bool operator==(const Coord &other) const
++    {
++        return X == other.X && Y == other.Y;
++    }
++
++    bool operator!=(const Coord &other) const
++    {
++        return !(*this == other);
++    }
++
++    Coord operator+(const Coord &other) const
++    {
++        return Coord(X + other.X, Y + other.Y);
++    }
++
++    bool isEmpty() const
++    {
++        return X <= 0 || Y <= 0;
++    }
++
++    std::string toString() const
++    {
++        char ret[32];
++        winpty_snprintf(ret, "(%d,%d)", X, Y);
++        return std::string(ret);
++    }
++};
++
++#endif // COORD_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..191b2e1466af6488c265717385b3de778644ac06
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,239 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "DebugShowInput.h"
++
++#include <windows.h>
++#include <stdint.h>
++#include <stdio.h>
++#include <stdlib.h>
++
++#include <string>
++
++#include "../shared/StringBuilder.h"
++#include "InputMap.h"
++
++namespace {
++
++struct Flag {
++    DWORD value;
++    const char *text;
++};
++
++static const Flag kButtonStates[] = {
++    { FROM_LEFT_1ST_BUTTON_PRESSED, "1" },
++    { FROM_LEFT_2ND_BUTTON_PRESSED, "2" },
++    { FROM_LEFT_3RD_BUTTON_PRESSED, "3" },
++    { FROM_LEFT_4TH_BUTTON_PRESSED, "4" },
++    { RIGHTMOST_BUTTON_PRESSED,     "R" },
++};
++
++static const Flag kControlKeyStates[] = {
++    { CAPSLOCK_ON,          "CapsLock"      },
++    { ENHANCED_KEY,         "Enhanced"      },
++    { LEFT_ALT_PRESSED,     "LAlt"          },
++    { LEFT_CTRL_PRESSED,    "LCtrl"         },
++    { NUMLOCK_ON,           "NumLock"       },
++    { RIGHT_ALT_PRESSED,    "RAlt"          },
++    { RIGHT_CTRL_PRESSED,   "RCtrl"         },
++    { SCROLLLOCK_ON,        "ScrollLock"    },
++    { SHIFT_PRESSED,        "Shift"         },
++};
++
++static const Flag kMouseEventFlags[] = {
++    { DOUBLE_CLICK,         "Double"        },
++    { 8/*MOUSE_HWHEELED*/,  "HWheel"        },
++    { MOUSE_MOVED,          "Move"          },
++    { MOUSE_WHEELED,        "Wheel"         },
++};
++
++static void writeFlags(StringBuilder &out, DWORD flags,
++                       const char *remainderName,
++                       const Flag *table, size_t tableSize,
++                       char pre, char sep, char post) {
++    DWORD remaining = flags;
++    bool wroteSomething = false;
++    for (size_t i = 0; i < tableSize; ++i) {
++        const Flag &f = table[i];
++        if ((f.value & flags) == f.value) {
++            if (!wroteSomething && pre != '\0') {
++                out << pre;
++            } else if (wroteSomething && sep != '\0') {
++                out << sep;
++            }
++            out << f.text;
++            wroteSomething = true;
++            remaining &= ~f.value;
++        }
++    }
++    if (remaining != 0) {
++        if (!wroteSomething && pre != '\0') {
++            out << pre;
++        } else if (wroteSomething && sep != '\0') {
++            out << sep;
++        }
++        out << remainderName << "(0x" << hexOfInt(remaining) << ')';
++        wroteSomething = true;
++    }
++    if (wroteSomething && post != '\0') {
++        out << post;
++    }
++}
++
++template <size_t n>
++static void writeFlags(StringBuilder &out, DWORD flags,
++                       const char *remainderName,
++                       const Flag (&table)[n],
++                       char pre, char sep, char post) {
++    writeFlags(out, flags, remainderName, table, n, pre, sep, post);
++}
++
++} // anonymous namespace
++
++std::string controlKeyStatePrefix(DWORD controlKeyState) {
++    StringBuilder sb;
++    writeFlags(sb, controlKeyState,
++               "keyState", kControlKeyStates, '\0', '-', '-');
++    return sb.str_moved();
++}
++
++std::string mouseEventToString(const MOUSE_EVENT_RECORD &mer) {
++    const uint16_t buttons = mer.dwButtonState & 0xFFFF;
++    const int16_t wheel = mer.dwButtonState >> 16;
++    StringBuilder sb;
++    sb << "pos=" << mer.dwMousePosition.X << ','
++                 << mer.dwMousePosition.Y;
++    writeFlags(sb, mer.dwControlKeyState, "keyState", kControlKeyStates, ' ', ' ', '\0');
++    writeFlags(sb, mer.dwEventFlags, "flags", kMouseEventFlags, ' ', ' ', '\0');
++    writeFlags(sb, buttons, "buttons", kButtonStates, ' ', ' ', '\0');
++    if (wheel != 0) {
++        sb << " wheel=" << wheel;
++    }
++    return sb.str_moved();
++}
++
++void debugShowInput(bool enableMouse, bool escapeInput) {
++    HANDLE conin = GetStdHandle(STD_INPUT_HANDLE);
++    DWORD origConsoleMode = 0;
++    if (!GetConsoleMode(conin, &origConsoleMode)) {
++        fprintf(stderr, "Error: could not read console mode -- "
++                        "is STDIN a console handle?\n");
++        exit(1);
++    }
++    DWORD restoreConsoleMode = origConsoleMode;
++    if (enableMouse && !(restoreConsoleMode & ENABLE_EXTENDED_FLAGS)) {
++        // We need to disable QuickEdit mode, because it blocks mouse events.
++        // If ENABLE_EXTENDED_FLAGS wasn't originally in the console mode, then
++        // we have no way of knowning whether QuickEdit or InsertMode are
++        // currently enabled.  Enable them both (eventually), because they're
++        // sensible defaults.  This case shouldn't happen typically.  See
++        // misc/EnableExtendedFlags.txt.
++        restoreConsoleMode |= ENABLE_EXTENDED_FLAGS;
++        restoreConsoleMode |= ENABLE_QUICK_EDIT_MODE;
++        restoreConsoleMode |= ENABLE_INSERT_MODE;
++    }
++    DWORD newConsoleMode = restoreConsoleMode;
++    newConsoleMode &= ~ENABLE_PROCESSED_INPUT;
++    newConsoleMode &= ~ENABLE_LINE_INPUT;
++    newConsoleMode &= ~ENABLE_ECHO_INPUT;
++    newConsoleMode |= ENABLE_WINDOW_INPUT;
++    if (enableMouse) {
++        newConsoleMode |= ENABLE_MOUSE_INPUT;
++        newConsoleMode &= ~ENABLE_QUICK_EDIT_MODE;
++    } else {
++        newConsoleMode &= ~ENABLE_MOUSE_INPUT;
++    }
++    if (escapeInput) {
++        // As of this writing (2016-06-05), Microsoft has shipped two preview
++        // builds of Windows 10 (14316 and 14342) that include a new "Windows
++        // Subsystem for Linux" that runs Ubuntu in a new subsystem.  Running
++        // bash in this subsystem requires the non-legacy console mode, and the
++        // console input buffer is put into a special mode where escape
++        // sequences are written into the console input buffer.  This mode is
++        // enabled with the 0x200 flag, which is as-yet undocumented.
++        // See https://github.com/rprichard/winpty/issues/82.
++        newConsoleMode |= 0x200;
++    }
++    if (!SetConsoleMode(conin, newConsoleMode)) {
++        fprintf(stderr, "Error: could not set console mode "
++            "(0x%x -> 0x%x -> 0x%x)\n",
++            static_cast<unsigned int>(origConsoleMode),
++            static_cast<unsigned int>(newConsoleMode),
++            static_cast<unsigned int>(restoreConsoleMode));
++        exit(1);
++    }
++    printf("\nPress any keys -- Ctrl-D exits\n\n");
++    INPUT_RECORD records[32];
++    DWORD actual = 0;
++    bool finished = false;
++    while (!finished &&
++            ReadConsoleInputW(conin, records, 32, &actual) && actual >= 1) {
++        StringBuilder sb;
++        for (DWORD i = 0; i < actual; ++i) {
++            const INPUT_RECORD &record = records[i];
++            if (record.EventType == KEY_EVENT) {
++                const KEY_EVENT_RECORD &ker = record.Event.KeyEvent;
++                InputMap::Key key = {
++                    ker.wVirtualKeyCode,
++                    ker.uChar.UnicodeChar,
++                    static_cast<uint16_t>(ker.dwControlKeyState),
++                };
++                sb << "key: " << (ker.bKeyDown ? "dn" : "up")
++                   << " rpt=" << ker.wRepeatCount
++                   << " scn=" << (ker.wVirtualScanCode ? "0x" : "") << hexOfInt(ker.wVirtualScanCode)
++                   << ' ' << key.toString() << '\n';
++                if ((ker.dwControlKeyState &
++                        (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) &&
++                        ker.wVirtualKeyCode == 'D') {
++                    finished = true;
++                    break;
++                } else if (ker.wVirtualKeyCode == 0 &&
++                        ker.wVirtualScanCode == 0 &&
++                        ker.uChar.UnicodeChar == 4) {
++                    // Also look for a zeroed-out Ctrl-D record generated for
++                    // ENABLE_VIRTUAL_TERMINAL_INPUT.
++                    finished = true;
++                    break;
++                }
++            } else if (record.EventType == MOUSE_EVENT) {
++                const MOUSE_EVENT_RECORD &mer = record.Event.MouseEvent;
++                sb << "mouse: " << mouseEventToString(mer) << '\n';
++            } else if (record.EventType == WINDOW_BUFFER_SIZE_EVENT) {
++                const WINDOW_BUFFER_SIZE_RECORD &wbsr =
++                    record.Event.WindowBufferSizeEvent;
++                sb << "buffer-resized: dwSize=("
++                   << wbsr.dwSize.X << ','
++                   << wbsr.dwSize.Y << ")\n";
++            } else if (record.EventType == MENU_EVENT) {
++                const MENU_EVENT_RECORD &mer = record.Event.MenuEvent;
++                sb << "menu-event: commandId=0x"
++                   << hexOfInt(mer.dwCommandId) << '\n';
++            } else if (record.EventType == FOCUS_EVENT) {
++                const FOCUS_EVENT_RECORD &fer = record.Event.FocusEvent;
++                sb << "focus: " << (fer.bSetFocus ? "gained" : "lost") << '\n';
++            }
++        }
++
++        const auto str = sb.str_moved();
++        fwrite(str.data(), 1, str.size(), stdout);
++        fflush(stdout);
++    }
++    SetConsoleMode(conin, restoreConsoleMode);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4fa13604bd43bb6f634aa3473b35a1e8a97a2bc5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,32 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_DEBUG_SHOW_INPUT_H
++#define AGENT_DEBUG_SHOW_INPUT_H
++
++#include <windows.h>
++
++#include <string>
++
++std::string controlKeyStatePrefix(DWORD controlKeyState);
++std::string mouseEventToString(const MOUSE_EVENT_RECORD &mer);
++void debugShowInput(bool enableMouse, bool escapeInput);
++
++#endif // AGENT_DEBUG_SHOW_INPUT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..5e29d98e4ec5a5e85daef66a63134ef31af88a66
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,422 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "DefaultInputMap.h"
++
++#include <windows.h>
++#include <string.h>
++
++#include <algorithm>
++
++#include "../shared/StringBuilder.h"
++#include "../shared/WinptyAssert.h"
++#include "InputMap.h"
++
++#define ESC "\x1B"
++#define DIM(x) (sizeof(x) / sizeof((x)[0]))
++
++namespace {
++
++struct EscapeEncoding {
++    bool alt_prefix_allowed;
++    char prefix;
++    char id;
++    int modifiers;
++    InputMap::Key key;
++};
++
++// Modifiers.  A "modifier" is an integer from 2 to 8 that conveys the status
++// of Shift(1), Alt(2), and Ctrl(4).  The value is constructed by OR'ing the
++// appropriate value for each active modifier, then adding 1.
++//
++// Details:
++//  - kBare:    expands to: ESC <prefix> <suffix>
++//  - kSemiMod: expands to: ESC <prefix> <numid> ; <mod> <suffix>
++//  - kBareMod: expands to: ESC <prefix> <mod> <suffix>
++const int kBare        = 0x01;
++const int kSemiMod     = 0x02;
++const int kBareMod     = 0x04;
++
++// Numeric escape sequences suffixes:
++//  - with no flag: accept: ~
++//  - kSuffixCtrl:  accept: ~ ^
++//  - kSuffixShift: accept: ~ $
++//  - kSuffixBoth:  accept: ~ ^ $ @
++const int kSuffixCtrl  = 0x08;
++const int kSuffixShift = 0x10;
++const int kSuffixBoth  = kSuffixCtrl | kSuffixShift;
++
++static const EscapeEncoding escapeLetterEncodings[] = {
++    // Conventional arrow keys
++    // kBareMod: Ubuntu /etc/inputrc and IntelliJ/JediTerm use escapes like: ESC [ n ABCD
++    { true,  '[', 'A', kBare | kBareMod | kSemiMod, { VK_UP,      '\0', 0             } },
++    { true,  '[', 'B', kBare | kBareMod | kSemiMod, { VK_DOWN,    '\0', 0             } },
++    { true,  '[', 'C', kBare | kBareMod | kSemiMod, { VK_RIGHT,   '\0', 0             } },
++    { true,  '[', 'D', kBare | kBareMod | kSemiMod, { VK_LEFT,    '\0', 0             } },
++
++    // putty.  putty uses this sequence for Ctrl-Arrow, Shift-Arrow, and
++    // Ctrl-Shift-Arrow, but I can only decode to one choice, so I'm just
++    // leaving the modifier off altogether.
++    { true,  'O', 'A', kBare,                       { VK_UP,      '\0', 0             } },
++    { true,  'O', 'B', kBare,                       { VK_DOWN,    '\0', 0             } },
++    { true,  'O', 'C', kBare,                       { VK_RIGHT,   '\0', 0             } },
++    { true,  'O', 'D', kBare,                       { VK_LEFT,    '\0', 0             } },
++
++    // rxvt, rxvt-unicode
++    // Shift-Ctrl-Arrow can't be identified.  It's the same as Shift-Arrow.
++    { true,  '[', 'a', kBare,                       { VK_UP,      '\0', SHIFT_PRESSED       } },
++    { true,  '[', 'b', kBare,                       { VK_DOWN,    '\0', SHIFT_PRESSED       } },
++    { true,  '[', 'c', kBare,                       { VK_RIGHT,   '\0', SHIFT_PRESSED       } },
++    { true,  '[', 'd', kBare,                       { VK_LEFT,    '\0', SHIFT_PRESSED       } },
++    { true,  'O', 'a', kBare,                       { VK_UP,      '\0', LEFT_CTRL_PRESSED   } },
++    { true,  'O', 'b', kBare,                       { VK_DOWN,    '\0', LEFT_CTRL_PRESSED   } },
++    { true,  'O', 'c', kBare,                       { VK_RIGHT,   '\0', LEFT_CTRL_PRESSED   } },
++    { true,  'O', 'd', kBare,                       { VK_LEFT,    '\0', LEFT_CTRL_PRESSED   } },
++
++    // Numpad 5 with NumLock off
++    //  * xterm, mintty, and gnome-terminal use `ESC [ E`.
++    //  * putty, TERM=cygwin, TERM=linux all use `ESC [ G` for 5
++    //  * putty uses `ESC O G` for Ctrl-5 and Shift-5.  Omit the modifier
++    //    as with putty's arrow keys.
++    //  * I never saw modifiers inserted into these escapes, but I think
++    //    it should be completely OK with the CSI escapes.
++    { true,  '[', 'E', kBare | kSemiMod,            { VK_CLEAR,   '\0', 0             } },
++    { true,  '[', 'G', kBare | kSemiMod,            { VK_CLEAR,   '\0', 0             } },
++    { true,  'O', 'G', kBare,                       { VK_CLEAR,   '\0', 0             } },
++
++    // Home/End, letter version
++    //  * gnome-terminal uses `ESC O [HF]`.  I never saw it modified.
++    // kBareMod: IntelliJ/JediTerm uses escapes like: ESC [ n HF
++    { true,  '[', 'H', kBare | kBareMod | kSemiMod, { VK_HOME,    '\0', 0             } },
++    { true,  '[', 'F', kBare | kBareMod | kSemiMod, { VK_END,     '\0', 0             } },
++    { true,  'O', 'H', kBare,                       { VK_HOME,    '\0', 0             } },
++    { true,  'O', 'F', kBare,                       { VK_END,     '\0', 0             } },
++
++    // F1-F4, letter version (xterm, VTE, konsole)
++    { true,  '[', 'P', kSemiMod,                    { VK_F1,      '\0', 0             } },
++    { true,  '[', 'Q', kSemiMod,                    { VK_F2,      '\0', 0             } },
++    { true,  '[', 'R', kSemiMod,                    { VK_F3,      '\0', 0             } },
++    { true,  '[', 'S', kSemiMod,                    { VK_F4,      '\0', 0             } },
++
++    // GNOME VTE and Konsole have special encodings for modified F1-F4:
++    //  * [VTE]     ESC O 1 ; n [PQRS]
++    //  * [Konsole] ESC O     n [PQRS]
++    { false, 'O', 'P', kBare | kBareMod | kSemiMod, { VK_F1,      '\0', 0             } },
++    { false, 'O', 'Q', kBare | kBareMod | kSemiMod, { VK_F2,      '\0', 0             } },
++    { false, 'O', 'R', kBare | kBareMod | kSemiMod, { VK_F3,      '\0', 0             } },
++    { false, 'O', 'S', kBare | kBareMod | kSemiMod, { VK_F4,      '\0', 0             } },
++
++    // Handle the "application numpad" escape sequences.
++    //
++    // Terminals output these codes under various circumstances:
++    //  * rxvt-unicode: numpad, hold down SHIFT
++    //  * rxvt: numpad, by default
++    //  * xterm: numpad, after enabling app-mode using DECPAM (`ESC =`).  xterm
++    //    generates `ESC O <mod> <letter>` for modified numpad presses,
++    //    necessitating kBareMod.
++    //  * mintty: by combining Ctrl with various keys such as '1' or ','.
++    //    Handling those keys is difficult, because mintty is generating the
++    //    same sequence for Ctrl-1 and Ctrl-NumPadEnd -- should the virtualKey
++    //    be '1' or VK_HOME?
++
++    { true,  'O', 'M', kBare | kBareMod,            { VK_RETURN,   '\r',   0 } },
++    { true,  'O', 'j', kBare | kBareMod,            { VK_MULTIPLY, '*',    0 } },
++    { true,  'O', 'k', kBare | kBareMod,            { VK_ADD,      '+',    0 } },
++    { true,  'O', 'm', kBare | kBareMod,            { VK_SUBTRACT, '-',    0 } },
++    { true,  'O', 'n', kBare | kBareMod,            { VK_DELETE,   '\0',   0 } },
++    { true,  'O', 'o', kBare | kBareMod,            { VK_DIVIDE,   '/',    0 } },
++    { true,  'O', 'p', kBare | kBareMod,            { VK_INSERT,   '\0',   0 } },
++    { true,  'O', 'q', kBare | kBareMod,            { VK_END,      '\0',   0 } },
++    { true,  'O', 'r', kBare | kBareMod,            { VK_DOWN,     '\0',   0 } },
++    { true,  'O', 's', kBare | kBareMod,            { VK_NEXT,     '\0',   0 } },
++    { true,  'O', 't', kBare | kBareMod,            { VK_LEFT,     '\0',   0 } },
++    { true,  'O', 'u', kBare | kBareMod,            { VK_CLEAR,    '\0',   0 } },
++    { true,  'O', 'v', kBare | kBareMod,            { VK_RIGHT,    '\0',   0 } },
++    { true,  'O', 'w', kBare | kBareMod,            { VK_HOME,     '\0',   0 } },
++    { true,  'O', 'x', kBare | kBareMod,            { VK_UP,       '\0',   0 } },
++    { true,  'O', 'y', kBare | kBareMod,            { VK_PRIOR,    '\0',   0 } },
++
++    { true,  '[', 'M', kBare | kSemiMod,            { VK_RETURN,   '\r',   0 } },
++    { true,  '[', 'j', kBare | kSemiMod,            { VK_MULTIPLY, '*',    0 } },
++    { true,  '[', 'k', kBare | kSemiMod,            { VK_ADD,      '+',    0 } },
++    { true,  '[', 'm', kBare | kSemiMod,            { VK_SUBTRACT, '-',    0 } },
++    { true,  '[', 'n', kBare | kSemiMod,            { VK_DELETE,   '\0',   0 } },
++    { true,  '[', 'o', kBare | kSemiMod,            { VK_DIVIDE,   '/',    0 } },
++    { true,  '[', 'p', kBare | kSemiMod,            { VK_INSERT,   '\0',   0 } },
++    { true,  '[', 'q', kBare | kSemiMod,            { VK_END,      '\0',   0 } },
++    { true,  '[', 'r', kBare | kSemiMod,            { VK_DOWN,     '\0',   0 } },
++    { true,  '[', 's', kBare | kSemiMod,            { VK_NEXT,     '\0',   0 } },
++    { true,  '[', 't', kBare | kSemiMod,            { VK_LEFT,     '\0',   0 } },
++    { true,  '[', 'u', kBare | kSemiMod,            { VK_CLEAR,    '\0',   0 } },
++    { true,  '[', 'v', kBare | kSemiMod,            { VK_RIGHT,    '\0',   0 } },
++    { true,  '[', 'w', kBare | kSemiMod,            { VK_HOME,     '\0',   0 } },
++    { true,  '[', 'x', kBare | kSemiMod,            { VK_UP,       '\0',   0 } },
++    { true,  '[', 'y', kBare | kSemiMod,            { VK_PRIOR,    '\0',   0 } },
++
++    { false, '[', 'Z', kBare,                       { VK_TAB,     '\t', SHIFT_PRESSED } },
++};
++
++static const EscapeEncoding escapeNumericEncodings[] = {
++    { true,  '[',  1,  kBare | kSemiMod | kSuffixBoth,      { VK_HOME,    '\0', 0             } },
++    { true,  '[',  2,  kBare | kSemiMod | kSuffixBoth,      { VK_INSERT,  '\0', 0             } },
++    { true,  '[',  3,  kBare | kSemiMod | kSuffixBoth,      { VK_DELETE,  '\0', 0             } },
++    { true,  '[',  4,  kBare | kSemiMod | kSuffixBoth,      { VK_END,     '\0', 0             } },
++    { true,  '[',  5,  kBare | kSemiMod | kSuffixBoth,      { VK_PRIOR,   '\0', 0             } },
++    { true,  '[',  6,  kBare | kSemiMod | kSuffixBoth,      { VK_NEXT,    '\0', 0             } },
++    { true,  '[',  7,  kBare | kSemiMod | kSuffixBoth,      { VK_HOME,    '\0', 0             } },
++    { true,  '[',  8,  kBare | kSemiMod | kSuffixBoth,      { VK_END,     '\0', 0             } },
++    { true,  '[', 11,  kBare | kSemiMod | kSuffixBoth,      { VK_F1,      '\0', 0             } },
++    { true,  '[', 12,  kBare | kSemiMod | kSuffixBoth,      { VK_F2,      '\0', 0             } },
++    { true,  '[', 13,  kBare | kSemiMod | kSuffixBoth,      { VK_F3,      '\0', 0             } },
++    { true,  '[', 14,  kBare | kSemiMod | kSuffixBoth,      { VK_F4,      '\0', 0             } },
++    { true,  '[', 15,  kBare | kSemiMod | kSuffixBoth,      { VK_F5,      '\0', 0             } },
++    { true,  '[', 17,  kBare | kSemiMod | kSuffixBoth,      { VK_F6,      '\0', 0             } },
++    { true,  '[', 18,  kBare | kSemiMod | kSuffixBoth,      { VK_F7,      '\0', 0             } },
++    { true,  '[', 19,  kBare | kSemiMod | kSuffixBoth,      { VK_F8,      '\0', 0             } },
++    { true,  '[', 20,  kBare | kSemiMod | kSuffixBoth,      { VK_F9,      '\0', 0             } },
++    { true,  '[', 21,  kBare | kSemiMod | kSuffixBoth,      { VK_F10,     '\0', 0             } },
++    { true,  '[', 23,  kBare | kSemiMod | kSuffixBoth,      { VK_F11,     '\0', 0             } },
++    { true,  '[', 24,  kBare | kSemiMod | kSuffixBoth,      { VK_F12,     '\0', 0             } },
++    { true,  '[', 25,  kBare | kSemiMod | kSuffixBoth,      { VK_F3,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 26,  kBare | kSemiMod | kSuffixBoth,      { VK_F4,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 28,  kBare | kSemiMod | kSuffixBoth,      { VK_F5,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 29,  kBare | kSemiMod | kSuffixBoth,      { VK_F6,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 31,  kBare | kSemiMod | kSuffixBoth,      { VK_F7,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 32,  kBare | kSemiMod | kSuffixBoth,      { VK_F8,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 33,  kBare | kSemiMod | kSuffixBoth,      { VK_F9,      '\0', SHIFT_PRESSED } },
++    { true,  '[', 34,  kBare | kSemiMod | kSuffixBoth,      { VK_F10,     '\0', SHIFT_PRESSED } },
++};
++
++const int kCsiShiftModifier = 1;
++const int kCsiAltModifier   = 2;
++const int kCsiCtrlModifier  = 4;
++
++static inline bool useEnhancedForVirtualKey(uint16_t vk) {
++    switch (vk) {
++        case VK_UP:
++        case VK_DOWN:
++        case VK_LEFT:
++        case VK_RIGHT:
++        case VK_INSERT:
++        case VK_DELETE:
++        case VK_HOME:
++        case VK_END:
++        case VK_PRIOR:
++        case VK_NEXT:
++            return true;
++        default:
++            return false;
++    }
++}
++
++static void addSimpleEntries(InputMap &inputMap) {
++    struct SimpleEncoding {
++        const char *encoding;
++        InputMap::Key key;
++    };
++
++    static const SimpleEncoding simpleEncodings[] = {
++        // Ctrl-<letter/digit> seems to be handled OK by the default code path.
++
++        {   "\x7F",         { VK_BACK,  '\x08', 0,                                  } },
++        {   ESC "\x7F",     { VK_BACK,  '\x08', LEFT_ALT_PRESSED,                   } },
++        {   "\x03",         { 'C',      '\x03', LEFT_CTRL_PRESSED,                  } },
++
++        // Handle special F1-F5 for TERM=linux and TERM=cygwin.
++        {   ESC "[[A",      { VK_F1,    '\0',   0                                   } },
++        {   ESC "[[B",      { VK_F2,    '\0',   0                                   } },
++        {   ESC "[[C",      { VK_F3,    '\0',   0                                   } },
++        {   ESC "[[D",      { VK_F4,    '\0',   0                                   } },
++        {   ESC "[[E",      { VK_F5,    '\0',   0                                   } },
++
++        {   ESC ESC "[[A",  { VK_F1,    '\0',   LEFT_ALT_PRESSED                    } },
++        {   ESC ESC "[[B",  { VK_F2,    '\0',   LEFT_ALT_PRESSED                    } },
++        {   ESC ESC "[[C",  { VK_F3,    '\0',   LEFT_ALT_PRESSED                    } },
++        {   ESC ESC "[[D",  { VK_F4,    '\0',   LEFT_ALT_PRESSED                    } },
++        {   ESC ESC "[[E",  { VK_F5,    '\0',   LEFT_ALT_PRESSED                    } },
++    };
++
++    for (size_t i = 0; i < DIM(simpleEncodings); ++i) {
++        auto k = simpleEncodings[i].key;
++        if (useEnhancedForVirtualKey(k.virtualKey)) {
++            k.keyState |= ENHANCED_KEY;
++        }
++        inputMap.set(simpleEncodings[i].encoding,
++                     strlen(simpleEncodings[i].encoding),
++                     k);
++    }
++}
++
++struct ExpandContext {
++    InputMap &inputMap;
++    const EscapeEncoding &e;
++    char *buffer;
++    char *bufferEnd;
++};
++
++static inline void setEncoding(const ExpandContext &ctx, char *end,
++                               uint16_t extraKeyState) {
++    InputMap::Key k = ctx.e.key;
++    k.keyState |= extraKeyState;
++    if (k.keyState & LEFT_CTRL_PRESSED) {
++        switch (k.virtualKey) {
++            case VK_ADD:
++            case VK_DIVIDE:
++            case VK_MULTIPLY:
++            case VK_SUBTRACT:
++                k.unicodeChar = '\0';
++                break;
++            case VK_RETURN:
++                k.unicodeChar = '\n';
++                break;
++        }
++    }
++    if (useEnhancedForVirtualKey(k.virtualKey)) {
++        k.keyState |= ENHANCED_KEY;
++    }
++    ctx.inputMap.set(ctx.buffer, end - ctx.buffer, k);
++}
++
++static inline uint16_t keyStateForMod(int mod) {
++    int ret = 0;
++    if ((mod - 1) & kCsiShiftModifier)  ret |= SHIFT_PRESSED;
++    if ((mod - 1) & kCsiAltModifier)    ret |= LEFT_ALT_PRESSED;
++    if ((mod - 1) & kCsiCtrlModifier)   ret |= LEFT_CTRL_PRESSED;
++    return ret;
++}
++
++static void expandNumericEncodingSuffix(const ExpandContext &ctx, char *p,
++        uint16_t extraKeyState) {
++    ASSERT(p <= ctx.bufferEnd - 1);
++    {
++        char *q = p;
++        *q++ = '~';
++        setEncoding(ctx, q, extraKeyState);
++    }
++    if (ctx.e.modifiers & kSuffixShift) {
++        char *q = p;
++        *q++ = '$';
++        setEncoding(ctx, q, extraKeyState | SHIFT_PRESSED);
++    }
++    if (ctx.e.modifiers & kSuffixCtrl) {
++        char *q = p;
++        *q++ = '^';
++        setEncoding(ctx, q, extraKeyState | LEFT_CTRL_PRESSED);
++    }
++    if (ctx.e.modifiers & (kSuffixCtrl | kSuffixShift)) {
++        char *q = p;
++        *q++ = '@';
++        setEncoding(ctx, q, extraKeyState | SHIFT_PRESSED | LEFT_CTRL_PRESSED);
++    }
++}
++
++template <bool is_numeric>
++static inline void expandEncodingAfterAltPrefix(
++        const ExpandContext &ctx, char *p, uint16_t extraKeyState) {
++    auto appendId = [&](char *&ptr) {
++        const auto idstr = decOfInt(ctx.e.id);
++        ASSERT(ptr <= ctx.bufferEnd - idstr.size());
++        std::copy(idstr.data(), idstr.data() + idstr.size(), ptr);
++        ptr += idstr.size();
++    };
++    ASSERT(p <= ctx.bufferEnd - 2);
++    *p++ = '\x1b';
++    *p++ = ctx.e.prefix;
++    if (ctx.e.modifiers & kBare) {
++        char *q = p;
++        if (is_numeric) {
++            appendId(q);
++            expandNumericEncodingSuffix(ctx, q, extraKeyState);
++        } else {
++            ASSERT(q <= ctx.bufferEnd - 1);
++            *q++ = ctx.e.id;
++            setEncoding(ctx, q, extraKeyState);
++        }
++    }
++    if (ctx.e.modifiers & kBareMod) {
++        ASSERT(!is_numeric && "kBareMod is invalid with numeric sequences");
++        for (int mod = 2; mod <= 8; ++mod) {
++            char *q = p;
++            ASSERT(q <= ctx.bufferEnd - 2);
++            *q++ = '0' + mod;
++            *q++ = ctx.e.id;
++            setEncoding(ctx, q, extraKeyState | keyStateForMod(mod));
++        }
++    }
++    if (ctx.e.modifiers & kSemiMod) {
++        for (int mod = 2; mod <= 8; ++mod) {
++            char *q = p;
++            if (is_numeric) {
++                appendId(q);
++                ASSERT(q <= ctx.bufferEnd - 2);
++                *q++ = ';';
++                *q++ = '0' + mod;
++                expandNumericEncodingSuffix(
++                    ctx, q, extraKeyState | keyStateForMod(mod));
++            } else {
++                ASSERT(q <= ctx.bufferEnd - 4);
++                *q++ = '1';
++                *q++ = ';';
++                *q++ = '0' + mod;
++                *q++ = ctx.e.id;
++                setEncoding(ctx, q, extraKeyState | keyStateForMod(mod));
++            }
++        }
++    }
++}
++
++template <bool is_numeric>
++static inline void expandEncoding(const ExpandContext &ctx) {
++    if (ctx.e.alt_prefix_allowed) {
++        // For better or for worse, this code expands all of:
++        //  *     ESC [       <key>     -- <key>
++        //  * ESC ESC [       <key>     -- Alt-<key>
++        //  *     ESC [ 1 ; 3 <key>     -- Alt-<key>
++        //  * ESC ESC [ 1 ; 3 <key>     -- Alt-<key> specified twice
++        // I suspect no terminal actually emits the last one (i.e. specifying
++        // the Alt modifier using both methods), but I have seen a terminal
++        // that emitted a prefix ESC for Alt and a non-Alt modifier.
++        char *p = ctx.buffer;
++        ASSERT(p <= ctx.bufferEnd - 1);
++        *p++ = '\x1b';
++        expandEncodingAfterAltPrefix<is_numeric>(ctx, p, LEFT_ALT_PRESSED);
++    }
++    expandEncodingAfterAltPrefix<is_numeric>(ctx, ctx.buffer, 0);
++}
++
++template <bool is_numeric, size_t N>
++static void addEscapes(InputMap &inputMap, const EscapeEncoding (&encodings)[N]) {
++    char buffer[32];
++    for (size_t i = 0; i < DIM(encodings); ++i) {
++        ExpandContext ctx = {
++            inputMap, encodings[i],
++            buffer, buffer + sizeof(buffer)
++        };
++        expandEncoding<is_numeric>(ctx);
++    }
++}
++
++} // anonymous namespace
++
++void addDefaultEntriesToInputMap(InputMap &inputMap) {
++    addEscapes<false>(inputMap, escapeLetterEncodings);
++    addEscapes<true>(inputMap, escapeNumericEncodings);
++    addSimpleEntries(inputMap);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c4b908367880a06cc677441d0107ce0928e5ddd2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,28 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef DEFAULT_INPUT_MAP_H
++#define DEFAULT_INPUT_MAP_H
++
++class InputMap;
++
++void addDefaultEntriesToInputMap(InputMap &inputMap);
++
++#endif // DEFAULT_INPUT_MAP_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1ec0a97d2e278e4602026db7d08821f8abe23c4b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,30 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef DSRSENDER_H
++#define DSRSENDER_H
++
++class DsrSender
++{
++public:
++    virtual void sendDsr() = 0;
++};
++
++#endif // DSRSENDER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ba5cf18cc8ad1ab5207937c363aeb9ac142fd42c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,99 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "EventLoop.h"
++
++#include <algorithm>
++
++#include "NamedPipe.h"
++#include "../shared/DebugClient.h"
++#include "../shared/WinptyAssert.h"
++
++EventLoop::~EventLoop() {
++    for (NamedPipe *pipe : m_pipes) {
++        delete pipe;
++    }
++    m_pipes.clear();
++}
++
++// Enter the event loop.  Runs until the I/O or timeout handler calls exit().
++void EventLoop::run()
++{
++    std::vector<HANDLE> waitHandles;
++    DWORD lastTime = GetTickCount();
++    while (!m_exiting) {
++        bool didSomething = false;
++
++        // Attempt to make progress with the pipes.
++        waitHandles.clear();
++        for (size_t i = 0; i < m_pipes.size(); ++i) {
++            if (m_pipes[i]->serviceIo(&waitHandles)) {
++                onPipeIo(*m_pipes[i]);
++                didSomething = true;
++            }
++        }
++
++        // Call the timeout if enough time has elapsed.
++        if (m_pollInterval > 0) {
++            int elapsed = GetTickCount() - lastTime;
++            if (elapsed >= m_pollInterval) {
++                onPollTimeout();
++                lastTime = GetTickCount();
++                didSomething = true;
++            }
++        }
++
++        if (didSomething)
++            continue;
++
++        // If there's nothing to do, wait.
++        DWORD timeout = INFINITE;
++        if (m_pollInterval > 0)
++            timeout = std::max(0, (int)(lastTime + m_pollInterval - GetTickCount()));
++        if (waitHandles.size() == 0) {
++            ASSERT(timeout != INFINITE);
++            if (timeout > 0)
++                Sleep(timeout);
++        } else {
++            DWORD result = WaitForMultipleObjects(waitHandles.size(),
++                                                  waitHandles.data(),
++                                                  FALSE,
++                                                  timeout);
++            ASSERT(result != WAIT_FAILED);
++        }
++    }
++}
++
++NamedPipe &EventLoop::createNamedPipe()
++{
++    NamedPipe *ret = new NamedPipe();
++    m_pipes.push_back(ret);
++    return *ret;
++}
++
++void EventLoop::setPollInterval(int ms)
++{
++    m_pollInterval = ms;
++}
++
++void EventLoop::shutdown()
++{
++    m_exiting = true;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..eddb0f62679f76af6d23893be534db6ea56ce875
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,47 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef EVENTLOOP_H
++#define EVENTLOOP_H
++
++#include <vector>
++
++class NamedPipe;
++
++class EventLoop
++{
++public:
++    virtual ~EventLoop();
++    void run();
++
++protected:
++    NamedPipe &createNamedPipe();
++    void setPollInterval(int ms);
++    void shutdown();
++    virtual void onPollTimeout()                    {}
++    virtual void onPipeIo(NamedPipe &namedPipe)     {}
++
++private:
++    bool m_exiting = false;
++    std::vector<NamedPipe*> m_pipes;
++    int m_pollInterval = 0;
++};
++
++#endif // EVENTLOOP_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b1fbfc2e3068b3ba945f783f114a68928fbe4844
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,246 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "InputMap.h"
++
++#include <windows.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include "DebugShowInput.h"
++#include "SimplePool.h"
++#include "../shared/DebugClient.h"
++#include "../shared/UnixCtrlChars.h"
++#include "../shared/WinptyAssert.h"
++#include "../shared/winpty_snprintf.h"
++
++namespace {
++
++static const char *getVirtualKeyString(int virtualKey)
++{
++    switch (virtualKey) {
++#define WINPTY_GVKS_KEY(x) case VK_##x: return #x;
++        WINPTY_GVKS_KEY(RBUTTON)    WINPTY_GVKS_KEY(F9)
++        WINPTY_GVKS_KEY(CANCEL)     WINPTY_GVKS_KEY(F10)
++        WINPTY_GVKS_KEY(MBUTTON)    WINPTY_GVKS_KEY(F11)
++        WINPTY_GVKS_KEY(XBUTTON1)   WINPTY_GVKS_KEY(F12)
++        WINPTY_GVKS_KEY(XBUTTON2)   WINPTY_GVKS_KEY(F13)
++        WINPTY_GVKS_KEY(BACK)       WINPTY_GVKS_KEY(F14)
++        WINPTY_GVKS_KEY(TAB)        WINPTY_GVKS_KEY(F15)
++        WINPTY_GVKS_KEY(CLEAR)      WINPTY_GVKS_KEY(F16)
++        WINPTY_GVKS_KEY(RETURN)     WINPTY_GVKS_KEY(F17)
++        WINPTY_GVKS_KEY(SHIFT)      WINPTY_GVKS_KEY(F18)
++        WINPTY_GVKS_KEY(CONTROL)    WINPTY_GVKS_KEY(F19)
++        WINPTY_GVKS_KEY(MENU)       WINPTY_GVKS_KEY(F20)
++        WINPTY_GVKS_KEY(PAUSE)      WINPTY_GVKS_KEY(F21)
++        WINPTY_GVKS_KEY(CAPITAL)    WINPTY_GVKS_KEY(F22)
++        WINPTY_GVKS_KEY(HANGUL)     WINPTY_GVKS_KEY(F23)
++        WINPTY_GVKS_KEY(JUNJA)      WINPTY_GVKS_KEY(F24)
++        WINPTY_GVKS_KEY(FINAL)      WINPTY_GVKS_KEY(NUMLOCK)
++        WINPTY_GVKS_KEY(KANJI)      WINPTY_GVKS_KEY(SCROLL)
++        WINPTY_GVKS_KEY(ESCAPE)     WINPTY_GVKS_KEY(LSHIFT)
++        WINPTY_GVKS_KEY(CONVERT)    WINPTY_GVKS_KEY(RSHIFT)
++        WINPTY_GVKS_KEY(NONCONVERT) WINPTY_GVKS_KEY(LCONTROL)
++        WINPTY_GVKS_KEY(ACCEPT)     WINPTY_GVKS_KEY(RCONTROL)
++        WINPTY_GVKS_KEY(MODECHANGE) WINPTY_GVKS_KEY(LMENU)
++        WINPTY_GVKS_KEY(SPACE)      WINPTY_GVKS_KEY(RMENU)
++        WINPTY_GVKS_KEY(PRIOR)      WINPTY_GVKS_KEY(BROWSER_BACK)
++        WINPTY_GVKS_KEY(NEXT)       WINPTY_GVKS_KEY(BROWSER_FORWARD)
++        WINPTY_GVKS_KEY(END)        WINPTY_GVKS_KEY(BROWSER_REFRESH)
++        WINPTY_GVKS_KEY(HOME)       WINPTY_GVKS_KEY(BROWSER_STOP)
++        WINPTY_GVKS_KEY(LEFT)       WINPTY_GVKS_KEY(BROWSER_SEARCH)
++        WINPTY_GVKS_KEY(UP)         WINPTY_GVKS_KEY(BROWSER_FAVORITES)
++        WINPTY_GVKS_KEY(RIGHT)      WINPTY_GVKS_KEY(BROWSER_HOME)
++        WINPTY_GVKS_KEY(DOWN)       WINPTY_GVKS_KEY(VOLUME_MUTE)
++        WINPTY_GVKS_KEY(SELECT)     WINPTY_GVKS_KEY(VOLUME_DOWN)
++        WINPTY_GVKS_KEY(PRINT)      WINPTY_GVKS_KEY(VOLUME_UP)
++        WINPTY_GVKS_KEY(EXECUTE)    WINPTY_GVKS_KEY(MEDIA_NEXT_TRACK)
++        WINPTY_GVKS_KEY(SNAPSHOT)   WINPTY_GVKS_KEY(MEDIA_PREV_TRACK)
++        WINPTY_GVKS_KEY(INSERT)     WINPTY_GVKS_KEY(MEDIA_STOP)
++        WINPTY_GVKS_KEY(DELETE)     WINPTY_GVKS_KEY(MEDIA_PLAY_PAUSE)
++        WINPTY_GVKS_KEY(HELP)       WINPTY_GVKS_KEY(LAUNCH_MAIL)
++        WINPTY_GVKS_KEY(LWIN)       WINPTY_GVKS_KEY(LAUNCH_MEDIA_SELECT)
++        WINPTY_GVKS_KEY(RWIN)       WINPTY_GVKS_KEY(LAUNCH_APP1)
++        WINPTY_GVKS_KEY(APPS)       WINPTY_GVKS_KEY(LAUNCH_APP2)
++        WINPTY_GVKS_KEY(SLEEP)      WINPTY_GVKS_KEY(OEM_1)
++        WINPTY_GVKS_KEY(NUMPAD0)    WINPTY_GVKS_KEY(OEM_PLUS)
++        WINPTY_GVKS_KEY(NUMPAD1)    WINPTY_GVKS_KEY(OEM_COMMA)
++        WINPTY_GVKS_KEY(NUMPAD2)    WINPTY_GVKS_KEY(OEM_MINUS)
++        WINPTY_GVKS_KEY(NUMPAD3)    WINPTY_GVKS_KEY(OEM_PERIOD)
++        WINPTY_GVKS_KEY(NUMPAD4)    WINPTY_GVKS_KEY(OEM_2)
++        WINPTY_GVKS_KEY(NUMPAD5)    WINPTY_GVKS_KEY(OEM_3)
++        WINPTY_GVKS_KEY(NUMPAD6)    WINPTY_GVKS_KEY(OEM_4)
++        WINPTY_GVKS_KEY(NUMPAD7)    WINPTY_GVKS_KEY(OEM_5)
++        WINPTY_GVKS_KEY(NUMPAD8)    WINPTY_GVKS_KEY(OEM_6)
++        WINPTY_GVKS_KEY(NUMPAD9)    WINPTY_GVKS_KEY(OEM_7)
++        WINPTY_GVKS_KEY(MULTIPLY)   WINPTY_GVKS_KEY(OEM_8)
++        WINPTY_GVKS_KEY(ADD)        WINPTY_GVKS_KEY(OEM_102)
++        WINPTY_GVKS_KEY(SEPARATOR)  WINPTY_GVKS_KEY(PROCESSKEY)
++        WINPTY_GVKS_KEY(SUBTRACT)   WINPTY_GVKS_KEY(PACKET)
++        WINPTY_GVKS_KEY(DECIMAL)    WINPTY_GVKS_KEY(ATTN)
++        WINPTY_GVKS_KEY(DIVIDE)     WINPTY_GVKS_KEY(CRSEL)
++        WINPTY_GVKS_KEY(F1)         WINPTY_GVKS_KEY(EXSEL)
++        WINPTY_GVKS_KEY(F2)         WINPTY_GVKS_KEY(EREOF)
++        WINPTY_GVKS_KEY(F3)         WINPTY_GVKS_KEY(PLAY)
++        WINPTY_GVKS_KEY(F4)         WINPTY_GVKS_KEY(ZOOM)
++        WINPTY_GVKS_KEY(F5)         WINPTY_GVKS_KEY(NONAME)
++        WINPTY_GVKS_KEY(F6)         WINPTY_GVKS_KEY(PA1)
++        WINPTY_GVKS_KEY(F7)         WINPTY_GVKS_KEY(OEM_CLEAR)
++        WINPTY_GVKS_KEY(F8)
++#undef WINPTY_GVKS_KEY
++        default:                        return NULL;
++    }
++}
++
++} // anonymous namespace
++
++std::string InputMap::Key::toString() const {
++    std::string ret;
++    ret += controlKeyStatePrefix(keyState);
++    char buf[256];
++    const char *vkString = getVirtualKeyString(virtualKey);
++    if (vkString != NULL) {
++        ret += vkString;
++    } else if ((virtualKey >= 'A' && virtualKey <= 'Z') ||
++               (virtualKey >= '0' && virtualKey <= '9')) {
++        ret += static_cast<char>(virtualKey);
++    } else {
++        winpty_snprintf(buf, "%#x", virtualKey);
++        ret += buf;
++    }
++    if (unicodeChar >= 32 && unicodeChar <= 126) {
++        winpty_snprintf(buf, " ch='%c'",
++                        static_cast<char>(unicodeChar));
++    } else {
++        winpty_snprintf(buf, " ch=%#x",
++                        static_cast<unsigned int>(unicodeChar));
++    }
++    ret += buf;
++    return ret;
++}
++
++void InputMap::set(const char *encoding, int encodingLen, const Key &key) {
++    ASSERT(encodingLen > 0);
++    setHelper(m_root, encoding, encodingLen, key);
++}
++
++void InputMap::setHelper(Node &node, const char *encoding, int encodingLen, const Key &key) {
++    if (encodingLen == 0) {
++        node.key = key;
++    } else {
++        setHelper(getOrCreateChild(node, encoding[0]), encoding + 1, encodingLen - 1, key);
++    }
++}
++
++InputMap::Node &InputMap::getOrCreateChild(Node &node, unsigned char ch) {
++    Node *ret = getChild(node, ch);
++    if (ret != NULL) {
++        return *ret;
++    }
++    if (node.childCount < Node::kTinyCount) {
++        // Maintain sorted order for the sake of the InputMap dumping.
++        int insertIndex = node.childCount;
++        for (int i = 0; i < node.childCount; ++i) {
++            if (ch < node.u.tiny.values[i]) {
++                insertIndex = i;
++                break;
++            }
++        }
++        for (int j = node.childCount; j > insertIndex; --j) {
++            node.u.tiny.values[j] = node.u.tiny.values[j - 1];
++            node.u.tiny.children[j] = node.u.tiny.children[j - 1];
++        }
++        node.u.tiny.values[insertIndex] = ch;
++        node.u.tiny.children[insertIndex] = ret = m_nodePool.alloc();
++        ++node.childCount;
++        return *ret;
++    }
++    if (node.childCount == Node::kTinyCount) {
++        Branch *branch = m_branchPool.alloc();
++        for (int i = 0; i < node.childCount; ++i) {
++            branch->children[node.u.tiny.values[i]] = node.u.tiny.children[i];
++        }
++        node.u.branch = branch;
++    }
++    node.u.branch->children[ch] = ret = m_nodePool.alloc();
++    ++node.childCount;
++    return *ret;
++}
++
++// Find the longest matching key and node.
++int InputMap::lookupKey(const char *input, int inputSize,
++                        Key &keyOut, bool &incompleteOut) const {
++    keyOut = kKeyZero;
++    incompleteOut = false;
++
++    const Node *node = &m_root;
++    InputMap::Key longestMatch = kKeyZero;
++    int longestMatchLen = 0;
++
++    for (int i = 0; i < inputSize; ++i) {
++        unsigned char ch = input[i];
++        node = getChild(*node, ch);
++        if (node == NULL) {
++            keyOut = longestMatch;
++            return longestMatchLen;
++        } else if (node->hasKey()) {
++            longestMatchLen = i + 1;
++            longestMatch = node->key;
++        }
++    }
++    keyOut = longestMatch;
++    incompleteOut = node->childCount > 0;
++    return longestMatchLen;
++}
++
++void InputMap::dumpInputMap() const {
++    std::string encoding;
++    dumpInputMapHelper(m_root, encoding);
++}
++
++void InputMap::dumpInputMapHelper(
++        const Node &node, std::string &encoding) const {
++    if (node.hasKey()) {
++        trace("%s -> %s",
++            encoding.c_str(),
++            node.key.toString().c_str());
++    }
++    for (int i = 0; i < 256; ++i) {
++        const Node *child = getChild(node, i);
++        if (child != NULL) {
++            size_t oldSize = encoding.size();
++            if (!encoding.empty()) {
++                encoding.push_back(' ');
++            }
++            char ctrlChar = decodeUnixCtrlChar(i);
++            if (ctrlChar != '\0') {
++                encoding.push_back('^');
++                encoding.push_back(static_cast<char>(ctrlChar));
++            } else if (i == ' ') {
++                encoding.append("' '");
++            } else {
++                encoding.push_back(static_cast<char>(i));
++            }
++            dumpInputMapHelper(*child, encoding);
++            encoding.resize(oldSize);
++        }
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9a666c79762362dffacb09b5751f860b05e27e7f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,114 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef INPUT_MAP_H
++#define INPUT_MAP_H
++
++#include <stdint.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include <string>
++
++#include "SimplePool.h"
++#include "../shared/WinptyAssert.h"
++
++class InputMap {
++public:
++    struct Key {
++        uint16_t virtualKey;
++        uint32_t unicodeChar;
++        uint16_t keyState;
++
++        std::string toString() const;
++    };
++
++private:
++    struct Node;
++
++    struct Branch {
++        Branch() {
++            memset(&children, 0, sizeof(children));
++        }
++
++        Node *children[256];
++    };
++
++    struct Node {
++        Node() : childCount(0) {
++            Key zeroKey = { 0, 0, 0 };
++            key = zeroKey;
++        }
++
++        Key key;
++        int childCount;
++        enum { kTinyCount = 8 };
++        union {
++            Branch *branch;
++            struct {
++                unsigned char values[kTinyCount];
++                Node *children[kTinyCount];
++            } tiny;
++        } u;
++
++        bool hasKey() const {
++            return key.virtualKey != 0 || key.unicodeChar != 0;
++        }
++    };
++
++private:
++    SimplePool<Node, 256> m_nodePool;
++    SimplePool<Branch, 8> m_branchPool;
++    Node m_root;
++
++public:
++    void set(const char *encoding, int encodingLen, const Key &key);
++    int lookupKey(const char *input, int inputSize,
++                  Key &keyOut, bool &incompleteOut) const;
++    void dumpInputMap() const;
++
++private:
++    Node *getChild(Node &node, unsigned char ch) {
++        return const_cast<Node*>(getChild(static_cast<const Node&>(node), ch));
++    }
++
++    const Node *getChild(const Node &node, unsigned char ch) const {
++        if (node.childCount <= Node::kTinyCount) {
++            for (int i = 0; i < node.childCount; ++i) {
++                if (node.u.tiny.values[i] == ch) {
++                    return node.u.tiny.children[i];
++                }
++            }
++            return NULL;
++        } else {
++            return node.u.branch->children[ch];
++        }
++    }
++
++    void setHelper(Node &node, const char *encoding, int encodingLen, const Key &key);
++    Node &getOrCreateChild(Node &node, unsigned char ch);
++    void dumpInputMapHelper(const Node &node, std::string &encoding) const;
++};
++
++const InputMap::Key kKeyZero = { 0, 0, 0 };
++
++void dumpInputMap(InputMap &inputMap);
++
++#endif // INPUT_MAP_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..80ac640e488bcdcc21fb276826a5960fa1b6723c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,71 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "LargeConsoleRead.h"
++
++#include <stdlib.h>
++
++#include "../shared/WindowsVersion.h"
++#include "Scraper.h"
++#include "Win32ConsoleBuffer.h"
++
++LargeConsoleReadBuffer::LargeConsoleReadBuffer() :
++    m_rect(0, 0, 0, 0), m_rectWidth(0)
++{
++}
++
++void largeConsoleRead(LargeConsoleReadBuffer &out,
++                      Win32ConsoleBuffer &buffer,
++                      const SmallRect &readArea,
++                      WORD attributesMask) {
++    ASSERT(readArea.Left >= 0 &&
++           readArea.Top >= 0 &&
++           readArea.Right >= readArea.Left &&
++           readArea.Bottom >= readArea.Top &&
++           readArea.width() <= MAX_CONSOLE_WIDTH);
++    const size_t count = readArea.width() * readArea.height();
++    if (out.m_data.size() < count) {
++        out.m_data.resize(count);
++    }
++    out.m_rect = readArea;
++    out.m_rectWidth = readArea.width();
++
++    static const bool useLargeReads = isAtLeastWindows8();
++    if (useLargeReads) {
++        buffer.read(readArea, out.m_data.data());
++    } else {
++        const int maxReadLines = std::max(1, MAX_CONSOLE_WIDTH / readArea.width());
++        int curLine = readArea.Top;
++        while (curLine <= readArea.Bottom) {
++            const SmallRect subReadArea(
++                readArea.Left,
++                curLine,
++                readArea.width(),
++                std::min(maxReadLines, readArea.Bottom + 1 - curLine));
++            buffer.read(subReadArea, out.lineDataMut(curLine));
++            curLine = subReadArea.Bottom + 1;
++        }
++    }
++    if (attributesMask != static_cast<WORD>(~0)) {
++        for (size_t i = 0; i < count; ++i) {
++            out.m_data[i].Attributes &= attributesMask;
++        }
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1bcf2c0232b97c66310a4eaecb5eae3146a03763
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,68 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef LARGE_CONSOLE_READ_H
++#define LARGE_CONSOLE_READ_H
++
++#include <windows.h>
++#include <stdlib.h>
++
++#include <vector>
++
++#include "SmallRect.h"
++#include "../shared/DebugClient.h"
++#include "../shared/WinptyAssert.h"
++
++class Win32ConsoleBuffer;
++
++class LargeConsoleReadBuffer {
++public:
++    LargeConsoleReadBuffer();
++    const SmallRect &rect() const { return m_rect; }
++    const CHAR_INFO *lineData(int line) const {
++        validateLineNumber(line);
++        return &m_data[(line - m_rect.Top) * m_rectWidth];
++    }
++
++private:
++    CHAR_INFO *lineDataMut(int line) {
++        validateLineNumber(line);
++        return &m_data[(line - m_rect.Top) * m_rectWidth];
++    }
++
++    void validateLineNumber(int line) const {
++        if (line < m_rect.Top || line > m_rect.Bottom) {
++            trace("Fatal error: LargeConsoleReadBuffer: invalid line %d for "
++                  "read rect %s", line, m_rect.toString().c_str());
++            abort();
++        }
++    }
++
++    SmallRect m_rect;
++    int m_rectWidth;
++    std::vector<CHAR_INFO> m_data;
++
++    friend void largeConsoleRead(LargeConsoleReadBuffer &out,
++                                 Win32ConsoleBuffer &buffer,
++                                 const SmallRect &readArea,
++                                 WORD attributesMask);
++};
++
++#endif // LARGE_CONSOLE_READ_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..64044e6e5d2391f3b43ce40b838305d9dbe4c22a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,378 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include <string.h>
++
++#include <algorithm>
++
++#include "EventLoop.h"
++#include "NamedPipe.h"
++#include "../shared/DebugClient.h"
++#include "../shared/StringUtil.h"
++#include "../shared/WindowsSecurity.h"
++#include "../shared/WinptyAssert.h"
++
++// Returns true if anything happens (data received, data sent, pipe error).
++bool NamedPipe::serviceIo(std::vector<HANDLE> *waitHandles)
++{
++    bool justConnected = false;
++    const auto kError = ServiceResult::Error;
++    const auto kProgress = ServiceResult::Progress;
++    const auto kNoProgress = ServiceResult::NoProgress;
++    if (m_handle == NULL) {
++        return false;
++    }
++    if (m_connectEvent.get() != nullptr) {
++        // We're still connecting this server pipe.  Check whether the pipe is
++        // now connected.  If it isn't, add the pipe to the list of handles to
++        // wait on.
++        DWORD actual = 0;
++        BOOL success =
++            GetOverlappedResult(m_handle, &m_connectOver, &actual, FALSE);
++        if (!success && GetLastError() == ERROR_PIPE_CONNECTED) {
++            // I'm not sure this can happen, but it's easy to handle if it
++            // does.
++            success = TRUE;
++        }
++        if (!success) {
++            ASSERT(GetLastError() == ERROR_IO_INCOMPLETE &&
++                "Pended ConnectNamedPipe call failed");
++            waitHandles->push_back(m_connectEvent.get());
++        } else {
++            TRACE("Server pipe [%s] connected",
++                utf8FromWide(m_name).c_str());
++            m_connectEvent.dispose();
++            startPipeWorkers();
++            justConnected = true;
++        }
++    }
++    const auto readProgress = m_inputWorker ? m_inputWorker->service() : kNoProgress;
++    const auto writeProgress = m_outputWorker ? m_outputWorker->service() : kNoProgress;
++    if (readProgress == kError || writeProgress == kError) {
++        closePipe();
++        return true;
++    }
++    if (m_inputWorker && m_inputWorker->getWaitEvent() != nullptr) {
++        waitHandles->push_back(m_inputWorker->getWaitEvent());
++    }
++    if (m_outputWorker && m_outputWorker->getWaitEvent() != nullptr) {
++        waitHandles->push_back(m_outputWorker->getWaitEvent());
++    }
++    return justConnected
++        || readProgress == kProgress
++        || writeProgress == kProgress;
++}
++
++// manual reset, initially unset
++static OwnedHandle createEvent() {
++    HANDLE ret = CreateEventW(nullptr, TRUE, FALSE, nullptr);
++    ASSERT(ret != nullptr && "CreateEventW failed");
++    return OwnedHandle(ret);
++}
++
++NamedPipe::IoWorker::IoWorker(NamedPipe &namedPipe) :
++    m_namedPipe(namedPipe),
++    m_event(createEvent())
++{
++}
++
++NamedPipe::ServiceResult NamedPipe::IoWorker::service()
++{
++    ServiceResult progress = ServiceResult::NoProgress;
++    if (m_pending) {
++        DWORD actual = 0;
++        BOOL ret = GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, FALSE);
++        if (!ret) {
++            if (GetLastError() == ERROR_IO_INCOMPLETE) {
++                // There is a pending I/O.
++                return progress;
++            } else {
++                // Pipe error.
++                return ServiceResult::Error;
++            }
++        }
++        ResetEvent(m_event.get());
++        m_pending = false;
++        completeIo(actual);
++        m_currentIoSize = 0;
++        progress = ServiceResult::Progress;
++    }
++    DWORD nextSize = 0;
++    bool isRead = false;
++    while (shouldIssueIo(&nextSize, &isRead)) {
++        m_currentIoSize = nextSize;
++        DWORD actual = 0;
++        memset(&m_over, 0, sizeof(m_over));
++        m_over.hEvent = m_event.get();
++        BOOL ret = isRead
++                ? ReadFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over)
++                : WriteFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over);
++        if (!ret) {
++            if (GetLastError() == ERROR_IO_PENDING) {
++                // There is a pending I/O.
++                m_pending = true;
++                return progress;
++            } else {
++                // Pipe error.
++                return ServiceResult::Error;
++            }
++        }
++        ResetEvent(m_event.get());
++        completeIo(actual);
++        m_currentIoSize = 0;
++        progress = ServiceResult::Progress;
++    }
++    return progress;
++}
++
++// This function is called after CancelIo has returned.  We need to block until
++// the I/O operations have completed, which should happen very quickly.
++// https://blogs.msdn.microsoft.com/oldnewthing/20110202-00/?p=11613
++void NamedPipe::IoWorker::waitForCanceledIo()
++{
++    if (m_pending) {
++        DWORD actual = 0;
++        GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, TRUE);
++        m_pending = false;
++    }
++}
++
++HANDLE NamedPipe::IoWorker::getWaitEvent()
++{
++    return m_pending ? m_event.get() : NULL;
++}
++
++void NamedPipe::InputWorker::completeIo(DWORD size)
++{
++    m_namedPipe.m_inQueue.append(m_buffer, size);
++}
++
++bool NamedPipe::InputWorker::shouldIssueIo(DWORD *size, bool *isRead)
++{
++    *isRead = true;
++    ASSERT(!m_namedPipe.isConnecting());
++    if (m_namedPipe.isClosed()) {
++        return false;
++    } else if (m_namedPipe.m_inQueue.size() < m_namedPipe.readBufferSize()) {
++        *size = kIoSize;
++        return true;
++    } else {
++        return false;
++    }
++}
++
++void NamedPipe::OutputWorker::completeIo(DWORD size)
++{
++    ASSERT(size == m_currentIoSize);
++}
++
++bool NamedPipe::OutputWorker::shouldIssueIo(DWORD *size, bool *isRead)
++{
++    *isRead = false;
++    if (!m_namedPipe.m_outQueue.empty()) {
++        auto &out = m_namedPipe.m_outQueue;
++        const DWORD writeSize = std::min<size_t>(out.size(), kIoSize);
++        std::copy(&out[0], &out[writeSize], m_buffer);
++        out.erase(0, writeSize);
++        *size = writeSize;
++        return true;
++    } else {
++        return false;
++    }
++}
++
++DWORD NamedPipe::OutputWorker::getPendingIoSize()
++{
++    return m_pending ? m_currentIoSize : 0;
++}
++
++void NamedPipe::openServerPipe(LPCWSTR pipeName, OpenMode::t openMode,
++                               int outBufferSize, int inBufferSize) {
++    ASSERT(isClosed());
++    ASSERT((openMode & OpenMode::Duplex) != 0);
++    const DWORD winOpenMode =
++              ((openMode & OpenMode::Reading) ? PIPE_ACCESS_INBOUND : 0)
++            | ((openMode & OpenMode::Writing) ? PIPE_ACCESS_OUTBOUND : 0)
++            | FILE_FLAG_FIRST_PIPE_INSTANCE
++            | FILE_FLAG_OVERLAPPED;
++    const auto sd = createPipeSecurityDescriptorOwnerFullControl();
++    ASSERT(sd && "error creating data pipe SECURITY_DESCRIPTOR");
++    SECURITY_ATTRIBUTES sa = {};
++    sa.nLength = sizeof(sa);
++    sa.lpSecurityDescriptor = sd.get();
++    HANDLE handle = CreateNamedPipeW(
++        pipeName,
++        /*dwOpenMode=*/winOpenMode,
++        /*dwPipeMode=*/rejectRemoteClientsPipeFlag(),
++        /*nMaxInstances=*/1,
++        /*nOutBufferSize=*/outBufferSize,
++        /*nInBufferSize=*/inBufferSize,
++        /*nDefaultTimeOut=*/30000,
++        &sa);
++    TRACE("opened server pipe [%s], handle == %p",
++        utf8FromWide(pipeName).c_str(), handle);
++    ASSERT(handle != INVALID_HANDLE_VALUE && "Could not open server pipe");
++    m_name = pipeName;
++    m_handle = handle;
++    m_openMode = openMode;
++
++    // Start an asynchronous connection attempt.
++    m_connectEvent = createEvent();
++    memset(&m_connectOver, 0, sizeof(m_connectOver));
++    m_connectOver.hEvent = m_connectEvent.get();
++    BOOL success = ConnectNamedPipe(m_handle, &m_connectOver);
++    const auto err = GetLastError();
++    if (!success && err == ERROR_PIPE_CONNECTED) {
++        success = TRUE;
++    }
++    if (success) {
++        TRACE("Server pipe [%s] connected", utf8FromWide(pipeName).c_str());
++        m_connectEvent.dispose();
++        startPipeWorkers();
++    } else if (err != ERROR_IO_PENDING) {
++        ASSERT(false && "ConnectNamedPipe call failed");
++    }
++}
++
++void NamedPipe::connectToServer(LPCWSTR pipeName, OpenMode::t openMode)
++{
++    ASSERT(isClosed());
++    ASSERT((openMode & OpenMode::Duplex) != 0);
++    HANDLE handle = CreateFileW(
++        pipeName,
++        GENERIC_READ | GENERIC_WRITE,
++        0,
++        NULL,
++        OPEN_EXISTING,
++        SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED,
++        NULL);
++    TRACE("connected to [%s], handle == %p",
++        utf8FromWide(pipeName).c_str(), handle);
++    ASSERT(handle != INVALID_HANDLE_VALUE && "Could not connect to pipe");
++    m_name = pipeName;
++    m_handle = handle;
++    m_openMode = openMode;
++    startPipeWorkers();
++}
++
++void NamedPipe::startPipeWorkers()
++{
++    if (m_openMode & OpenMode::Reading) {
++        m_inputWorker.reset(new InputWorker(*this));
++    }
++    if (m_openMode & OpenMode::Writing) {
++        m_outputWorker.reset(new OutputWorker(*this));
++    }
++}
++
++size_t NamedPipe::bytesToSend()
++{
++    ASSERT(m_openMode & OpenMode::Writing);
++    auto ret = m_outQueue.size();
++    if (m_outputWorker != NULL) {
++        ret += m_outputWorker->getPendingIoSize();
++    }
++    return ret;
++}
++
++void NamedPipe::write(const void *data, size_t size)
++{
++    ASSERT(m_openMode & OpenMode::Writing);
++    m_outQueue.append(reinterpret_cast<const char*>(data), size);
++}
++
++void NamedPipe::write(const char *text)
++{
++    write(text, strlen(text));
++}
++
++size_t NamedPipe::readBufferSize()
++{
++    ASSERT(m_openMode & OpenMode::Reading);
++    return m_readBufferSize;
++}
++
++void NamedPipe::setReadBufferSize(size_t size)
++{
++    ASSERT(m_openMode & OpenMode::Reading);
++    m_readBufferSize = size;
++}
++
++size_t NamedPipe::bytesAvailable()
++{
++    ASSERT(m_openMode & OpenMode::Reading);
++    return m_inQueue.size();
++}
++
++size_t NamedPipe::peek(void *data, size_t size)
++{
++    ASSERT(m_openMode & OpenMode::Reading);
++    const auto out = reinterpret_cast<char*>(data);
++    const size_t ret = std::min(size, m_inQueue.size());
++    std::copy(&m_inQueue[0], &m_inQueue[ret], out);
++    return ret;
++}
++
++size_t NamedPipe::read(void *data, size_t size)
++{
++    size_t ret = peek(data, size);
++    m_inQueue.erase(0, ret);
++    return ret;
++}
++
++std::string NamedPipe::readToString(size_t size)
++{
++    ASSERT(m_openMode & OpenMode::Reading);
++    size_t retSize = std::min(size, m_inQueue.size());
++    std::string ret = m_inQueue.substr(0, retSize);
++    m_inQueue.erase(0, retSize);
++    return ret;
++}
++
++std::string NamedPipe::readAllToString()
++{
++    ASSERT(m_openMode & OpenMode::Reading);
++    std::string ret = m_inQueue;
++    m_inQueue.clear();
++    return ret;
++}
++
++void NamedPipe::closePipe()
++{
++    if (m_handle == NULL) {
++        return;
++    }
++    CancelIo(m_handle);
++    if (m_connectEvent.get() != nullptr) {
++        DWORD actual = 0;
++        GetOverlappedResult(m_handle, &m_connectOver, &actual, TRUE);
++        m_connectEvent.dispose();
++    }
++    if (m_inputWorker) {
++        m_inputWorker->waitForCanceledIo();
++        m_inputWorker.reset();
++    }
++    if (m_outputWorker) {
++        m_outputWorker->waitForCanceledIo();
++        m_outputWorker.reset();
++    }
++    CloseHandle(m_handle);
++    m_handle = NULL;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0a4d8b0c75a802bde047a3a0f7b9928dc4b9f609
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,125 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef NAMEDPIPE_H
++#define NAMEDPIPE_H
++
++#include <windows.h>
++
++#include <memory>
++#include <string>
++#include <vector>
++
++#include "../shared/OwnedHandle.h"
++
++class EventLoop;
++
++class NamedPipe
++{
++private:
++    // The EventLoop uses these private members.
++    friend class EventLoop;
++    NamedPipe() {}
++    ~NamedPipe() { closePipe(); }
++    bool serviceIo(std::vector<HANDLE> *waitHandles);
++    void startPipeWorkers();
++
++    enum class ServiceResult { NoProgress, Error, Progress };
++
++private:
++    class IoWorker
++    {
++    public:
++        IoWorker(NamedPipe &namedPipe);
++        virtual ~IoWorker() {}
++        ServiceResult service();
++        void waitForCanceledIo();
++        HANDLE getWaitEvent();
++    protected:
++        NamedPipe &m_namedPipe;
++        bool m_pending = false;
++        DWORD m_currentIoSize = 0;
++        OwnedHandle m_event;
++        OVERLAPPED m_over = {};
++        enum { kIoSize = 64 * 1024 };
++        char m_buffer[kIoSize];
++        virtual void completeIo(DWORD size) = 0;
++        virtual bool shouldIssueIo(DWORD *size, bool *isRead) = 0;
++    };
++
++    class InputWorker : public IoWorker
++    {
++    public:
++        InputWorker(NamedPipe &namedPipe) : IoWorker(namedPipe) {}
++    protected:
++        virtual void completeIo(DWORD size) override;
++        virtual bool shouldIssueIo(DWORD *size, bool *isRead) override;
++    };
++
++    class OutputWorker : public IoWorker
++    {
++    public:
++        OutputWorker(NamedPipe &namedPipe) : IoWorker(namedPipe) {}
++        DWORD getPendingIoSize();
++    protected:
++        virtual void completeIo(DWORD size) override;
++        virtual bool shouldIssueIo(DWORD *size, bool *isRead) override;
++    };
++
++public:
++    struct OpenMode {
++        typedef int t;
++        enum { None = 0, Reading = 1, Writing = 2, Duplex = 3 };
++    };
++
++    std::wstring name() const { return m_name; }
++    void openServerPipe(LPCWSTR pipeName, OpenMode::t openMode,
++                        int outBufferSize, int inBufferSize);
++    void connectToServer(LPCWSTR pipeName, OpenMode::t openMode);
++    size_t bytesToSend();
++    void write(const void *data, size_t size);
++    void write(const char *text);
++    size_t readBufferSize();
++    void setReadBufferSize(size_t size);
++    size_t bytesAvailable();
++    size_t peek(void *data, size_t size);
++    size_t read(void *data, size_t size);
++    std::string readToString(size_t size);
++    std::string readAllToString();
++    void closePipe();
++    bool isClosed() { return m_handle == nullptr; }
++    bool isConnected() { return !isClosed() && !isConnecting(); }
++    bool isConnecting() { return m_connectEvent.get() != nullptr; }
++
++private:
++    // Input/output buffers
++    std::wstring m_name;
++    OVERLAPPED m_connectOver = {};
++    OwnedHandle m_connectEvent;
++    OpenMode::t m_openMode = OpenMode::None;
++    size_t m_readBufferSize = 64 * 1024;
++    std::string m_inQueue;
++    std::string m_outQueue;
++    HANDLE m_handle = nullptr;
++    std::unique_ptr<InputWorker> m_inputWorker;
++    std::unique_ptr<OutputWorker> m_outputWorker;
++};
++
++#endif // NAMEDPIPE_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..21f9c67104ebf83c9b992a6069bbbdb3f4490764
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,699 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Scraper.h"
++
++#include <windows.h>
++
++#include <stdint.h>
++
++#include <algorithm>
++#include <utility>
++
++#include "../shared/WinptyAssert.h"
++#include "../shared/winpty_snprintf.h"
++
++#include "ConsoleFont.h"
++#include "Win32Console.h"
++#include "Win32ConsoleBuffer.h"
++
++namespace {
++
++template <typename T>
++T constrained(T min, T val, T max) {
++    ASSERT(min <= max);
++    return std::min(std::max(min, val), max);
++}
++
++} // anonymous namespace
++
++Scraper::Scraper(
++        Win32Console &console,
++        Win32ConsoleBuffer &buffer,
++        std::unique_ptr<Terminal> terminal,
++        Coord initialSize) :
++    m_console(console),
++    m_terminal(std::move(terminal)),
++    m_ptySize(initialSize)
++{
++    m_consoleBuffer = &buffer;
++
++    resetConsoleTracking(Terminal::OmitClear, buffer.windowRect().top());
++
++    m_bufferData.resize(BUFFER_LINE_COUNT);
++
++    // Setup the initial screen buffer and window size.
++    //
++    // Use SetConsoleWindowInfo to shrink the console window as much as
++    // possible -- to a 1x1 cell at the top-left.  This call always succeeds.
++    // Prior to the new Windows 10 console, it also actually resizes the GUI
++    // window to 1x1 cell.  Nevertheless, even though the GUI window can
++    // therefore be narrower than its minimum, calling
++    // SetConsoleScreenBufferSize with a 1x1 size still fails.
++    //
++    // While the small font intends to support large buffers, a user could
++    // still hit a limit imposed by their monitor width, so cap the new window
++    // size to GetLargestConsoleWindowSize().
++    setSmallFont(buffer.conout(), initialSize.X, m_console.isNewW10());
++    buffer.moveWindow(SmallRect(0, 0, 1, 1));
++    buffer.resizeBufferRange(Coord(initialSize.X, BUFFER_LINE_COUNT));
++    const auto largest = GetLargestConsoleWindowSize(buffer.conout());
++    buffer.moveWindow(SmallRect(
++        0, 0,
++        std::min(initialSize.X, largest.X),
++        std::min(initialSize.Y, largest.Y)));
++    buffer.setCursorPosition(Coord(0, 0));
++
++    // For the sake of the color translation heuristic, set the console color
++    // to LtGray-on-Black.
++    buffer.setTextAttribute(Win32ConsoleBuffer::kDefaultAttributes);
++    buffer.clearAllLines(m_consoleBuffer->bufferInfo());
++
++    m_consoleBuffer = nullptr;
++}
++
++Scraper::~Scraper()
++{
++}
++
++// Whether or not the agent is frozen on entry, it will be frozen on exit.
++void Scraper::resizeWindow(Win32ConsoleBuffer &buffer,
++                           Coord newSize,
++                           ConsoleScreenBufferInfo &finalInfoOut)
++{
++    m_consoleBuffer = &buffer;
++    m_ptySize = newSize;
++    syncConsoleContentAndSize(true, finalInfoOut);
++    m_consoleBuffer = nullptr;
++}
++
++// This function may freeze the agent, but it will not unfreeze it.
++void Scraper::scrapeBuffer(Win32ConsoleBuffer &buffer,
++                           ConsoleScreenBufferInfo &finalInfoOut)
++{
++    m_consoleBuffer = &buffer;
++    syncConsoleContentAndSize(false, finalInfoOut);
++    m_consoleBuffer = nullptr;
++}
++
++void Scraper::resetConsoleTracking(
++    Terminal::SendClearFlag sendClear, int64_t scrapedLineCount)
++{
++    for (ConsoleLine &line : m_bufferData) {
++        line.reset();
++    }
++    m_syncRow = -1;
++    m_scrapedLineCount = scrapedLineCount;
++    m_scrolledCount = 0;
++    m_maxBufferedLine = -1;
++    m_dirtyWindowTop = -1;
++    m_dirtyLineCount = 0;
++    m_terminal->reset(sendClear, m_scrapedLineCount);
++}
++
++// Detect window movement.  If the window moves down (presumably as a
++// result of scrolling), then assume that all screen buffer lines down to
++// the bottom of the window are dirty.
++void Scraper::markEntireWindowDirty(const SmallRect &windowRect)
++{
++    m_dirtyLineCount = std::max(m_dirtyLineCount,
++                                windowRect.top() + windowRect.height());
++}
++
++// Scan the screen buffer and advance the dirty line count when we find
++// non-empty lines.
++void Scraper::scanForDirtyLines(const SmallRect &windowRect)
++{
++    const int w = m_readBuffer.rect().width();
++    ASSERT(m_dirtyLineCount >= 1);
++    const CHAR_INFO *const prevLine =
++        m_readBuffer.lineData(m_dirtyLineCount - 1);
++    WORD prevLineAttr = prevLine[w - 1].Attributes;
++    const int stopLine = windowRect.top() + windowRect.height();
++
++    for (int line = m_dirtyLineCount; line < stopLine; ++line) {
++        const CHAR_INFO *lineData = m_readBuffer.lineData(line);
++        for (int col = 0; col < w; ++col) {
++            const WORD colAttr = lineData[col].Attributes;
++            if (lineData[col].Char.UnicodeChar != L' ' ||
++                    colAttr != prevLineAttr) {
++                m_dirtyLineCount = line + 1;
++                break;
++            }
++        }
++        prevLineAttr = lineData[w - 1].Attributes;
++    }
++}
++
++// Clear lines in the line buffer.  The `firstRow` parameter is in
++// screen-buffer coordinates.
++void Scraper::clearBufferLines(
++        const int firstRow,
++        const int count)
++{
++    ASSERT(!m_directMode);
++    for (int row = firstRow; row < firstRow + count; ++row) {
++        const int64_t bufLine = row + m_scrolledCount;
++        m_maxBufferedLine = std::max(m_maxBufferedLine, bufLine);
++        m_bufferData[bufLine % BUFFER_LINE_COUNT].blank(
++            Win32ConsoleBuffer::kDefaultAttributes);
++    }
++}
++
++static bool cursorInWindow(const ConsoleScreenBufferInfo &info)
++{
++    return info.dwCursorPosition.Y >= info.srWindow.Top &&
++           info.dwCursorPosition.Y <= info.srWindow.Bottom;
++}
++
++void Scraper::resizeImpl(const ConsoleScreenBufferInfo &origInfo)
++{
++    ASSERT(m_console.frozen());
++    const int cols = m_ptySize.X;
++    const int rows = m_ptySize.Y;
++    Coord finalBufferSize;
++
++    {
++        //
++        // To accommodate Windows 10, erase all lines up to the top of the
++        // visible window.  It's hard to tell whether this is strictly
++        // necessary.  It ensures that the sync marker won't move downward,
++        // and it ensures that we won't repeat lines that have already scrolled
++        // up into the scrollback.
++        //
++        // It *is* possible for these blank lines to reappear in the visible
++        // window (e.g. if the window is made taller), but because we blanked
++        // the lines in the line buffer, we still don't output them again.
++        //
++        const Coord origBufferSize = origInfo.bufferSize();
++        const SmallRect origWindowRect = origInfo.windowRect();
++
++        if (m_directMode) {
++            for (ConsoleLine &line : m_bufferData) {
++                line.reset();
++            }
++        } else {
++            m_consoleBuffer->clearLines(0, origWindowRect.Top, origInfo);
++            clearBufferLines(0, origWindowRect.Top);
++            if (m_syncRow != -1) {
++                createSyncMarker(std::min(
++                    m_syncRow,
++                    BUFFER_LINE_COUNT - rows
++                                      - SYNC_MARKER_LEN
++                                      - SYNC_MARKER_MARGIN));
++            }
++        }
++
++        finalBufferSize = Coord(
++            cols,
++            // If there was previously no scrollback (e.g. a full-screen app
++            // in direct mode) and we're reducing the window height, then
++            // reduce the console buffer's height too.
++            (origWindowRect.height() == origBufferSize.Y)
++                ? rows
++                : std::max<int>(rows, origBufferSize.Y));
++
++        // Reset the console font size.  We need to do this before shrinking
++        // the window, because we might need to make the font bigger to permit
++        // a smaller window width.  Making the font smaller could expand the
++        // screen buffer, which would hang the conhost process in the
++        // Windows 10 (10240 build) if the console selection is in progress, so
++        // unfreeze it first.
++        m_console.setFrozen(false);
++        setSmallFont(m_consoleBuffer->conout(), cols, m_console.isNewW10());
++    }
++
++    // We try to make the font small enough so that the entire screen buffer
++    // fits on the monitor, but it can't be guaranteed.
++    const auto largest =
++        GetLargestConsoleWindowSize(m_consoleBuffer->conout());
++    const short visibleCols = std::min<short>(cols, largest.X);
++    const short visibleRows = std::min<short>(rows, largest.Y);
++
++    {
++        // Make the window small enough.  We want the console frozen during
++        // this step so we don't accidentally move the window above the cursor.
++        m_console.setFrozen(true);
++        const auto info = m_consoleBuffer->bufferInfo();
++        const auto &bufferSize = info.dwSize;
++        const int tmpWindowWidth = std::min(bufferSize.X, visibleCols);
++        const int tmpWindowHeight = std::min(bufferSize.Y, visibleRows);
++        SmallRect tmpWindowRect(
++            0,
++            std::min<int>(bufferSize.Y - tmpWindowHeight,
++                          info.windowRect().Top),
++            tmpWindowWidth,
++            tmpWindowHeight);
++        if (cursorInWindow(info)) {
++            tmpWindowRect = tmpWindowRect.ensureLineIncluded(
++                info.cursorPosition().Y);
++        }
++        m_consoleBuffer->moveWindow(tmpWindowRect);
++    }
++
++    {
++        // Resize the buffer to the final desired size.
++        m_console.setFrozen(false);
++        m_consoleBuffer->resizeBufferRange(finalBufferSize);
++    }
++
++    {
++        // Expand the window to its full size.
++        m_console.setFrozen(true);
++        const ConsoleScreenBufferInfo info = m_consoleBuffer->bufferInfo();
++
++        SmallRect finalWindowRect(
++            0,
++            std::min<int>(info.bufferSize().Y - visibleRows,
++                          info.windowRect().Top),
++            visibleCols,
++            visibleRows);
++
++        //
++        // Once a line in the screen buffer is "dirty", it should stay visible
++        // in the console window, so that we continue to update its content in
++        // the terminal.  This code is particularly (only?) necessary on
++        // Windows 10, where making the buffer wider can rewrap lines and move
++        // the console window upward.
++        //
++        if (!m_directMode && m_dirtyLineCount > finalWindowRect.Bottom + 1) {
++            // In theory, we avoid ensureLineIncluded, because, a massive
++            // amount of output could have occurred while the console was
++            // unfrozen, so that the *top* of the window is now below the
++            // dirtiest tracked line.
++            finalWindowRect = SmallRect(
++                0, m_dirtyLineCount - visibleRows,
++                visibleCols, visibleRows);
++        }
++
++        // Highest priority constraint: ensure that the cursor remains visible.
++        if (cursorInWindow(info)) {
++            finalWindowRect = finalWindowRect.ensureLineIncluded(
++                info.cursorPosition().Y);
++        }
++
++        m_consoleBuffer->moveWindow(finalWindowRect);
++        m_dirtyWindowTop = finalWindowRect.Top;
++    }
++
++    ASSERT(m_console.frozen());
++}
++
++void Scraper::syncConsoleContentAndSize(
++    bool forceResize,
++    ConsoleScreenBufferInfo &finalInfoOut)
++{
++    // We'll try to avoid freezing the console by reading large chunks (or
++    // all!) of the screen buffer without otherwise attempting to synchronize
++    // with the console application.  We can only do this on Windows 10 and up
++    // because:
++    //  - Prior to Windows 8, the size of a ReadConsoleOutputW call was limited
++    //    by the ~32KB RPC buffer.
++    //  - Prior to Windows 10, an out-of-range read region crashes the caller.
++    //    (See misc/WindowsBugCrashReader.cc.)
++    //
++    if (!m_console.isNewW10() || forceResize) {
++        m_console.setFrozen(true);
++    }
++
++    const ConsoleScreenBufferInfo info = m_consoleBuffer->bufferInfo();
++    bool cursorVisible = true;
++    CONSOLE_CURSOR_INFO cursorInfo = {};
++    if (!GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo)) {
++        trace("GetConsoleCursorInfo failed");
++    } else {
++        cursorVisible = cursorInfo.bVisible != 0;
++    }
++
++    // If an app resizes the buffer height, then we enter "direct mode", where
++    // we stop trying to track incremental console changes.
++    const bool newDirectMode = (info.bufferSize().Y != BUFFER_LINE_COUNT);
++    if (newDirectMode != m_directMode) {
++        trace("Entering %s mode", newDirectMode ? "direct" : "scrolling");
++        resetConsoleTracking(Terminal::SendClear,
++                             newDirectMode ? 0 : info.windowRect().top());
++        m_directMode = newDirectMode;
++
++        // When we switch from direct->scrolling mode, make sure the console is
++        // the right size.
++        if (!m_directMode) {
++            m_console.setFrozen(true);
++            forceResize = true;
++        }
++    }
++
++    if (m_directMode) {
++        // In direct-mode, resizing the console redraws the terminal, so do it
++        // before scraping.
++        if (forceResize) {
++            resizeImpl(info);
++        }
++        directScrapeOutput(info, cursorVisible);
++    } else {
++        if (!m_console.frozen()) {
++            if (!scrollingScrapeOutput(info, cursorVisible, true)) {
++                m_console.setFrozen(true);
++            }
++        }
++        if (m_console.frozen()) {
++            scrollingScrapeOutput(info, cursorVisible, false);
++        }
++        // In scrolling mode, we want to scrape before resizing, because we'll
++        // erase everything in the console buffer up to the top of the console
++        // window.
++        if (forceResize) {
++            resizeImpl(info);
++        }
++    }
++
++    finalInfoOut = forceResize ? m_consoleBuffer->bufferInfo() : info;
++}
++
++// Try to match Windows' behavior w.r.t. to the LVB attribute flags.  In some
++// situations, Windows ignores the LVB flags on a character cell because of
++// backwards compatibility -- apparently some programs set the flags without
++// intending to enable reverse-video or underscores.
++//
++// [rprichard 2017-01-15] I haven't actually noticed any old programs that need
++// this treatment -- the motivation for this function comes from the MSDN
++// documentation for SetConsoleMode and ENABLE_LVB_GRID_WORLDWIDE.
++WORD Scraper::attributesMask()
++{
++    const auto WINPTY_ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4u;
++    const auto WINPTY_ENABLE_LVB_GRID_WORLDWIDE          = 0x10u;
++    const auto WINPTY_COMMON_LVB_REVERSE_VIDEO           = 0x4000u;
++    const auto WINPTY_COMMON_LVB_UNDERSCORE              = 0x8000u;
++
++    const auto cp = GetConsoleOutputCP();
++    const auto isCjk = (cp == 932 || cp == 936 || cp == 949 || cp == 950);
++
++    const DWORD outputMode = [this]{
++        ASSERT(this->m_consoleBuffer != nullptr);
++        DWORD mode = 0;
++        if (!GetConsoleMode(this->m_consoleBuffer->conout(), &mode)) {
++            mode = 0;
++        }
++        return mode;
++    }();
++    const bool hasEnableLvbGridWorldwide =
++        (outputMode & WINPTY_ENABLE_LVB_GRID_WORLDWIDE) != 0;
++    const bool hasEnableVtProcessing =
++        (outputMode & WINPTY_ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;
++
++    // The new Windows 10 console (as of 14393) seems to respect
++    // COMMON_LVB_REVERSE_VIDEO even in CP437 w/o the other enabling modes, so
++    // try to match that behavior.
++    const auto isReverseSupported =
++        isCjk || hasEnableLvbGridWorldwide || hasEnableVtProcessing || m_console.isNewW10();
++    const auto isUnderscoreSupported =
++        isCjk || hasEnableLvbGridWorldwide || hasEnableVtProcessing;
++
++    WORD mask = ~0;
++    if (!isReverseSupported)    { mask &= ~WINPTY_COMMON_LVB_REVERSE_VIDEO; }
++    if (!isUnderscoreSupported) { mask &= ~WINPTY_COMMON_LVB_UNDERSCORE; }
++    return mask;
++}
++
++void Scraper::directScrapeOutput(const ConsoleScreenBufferInfo &info,
++                                 bool consoleCursorVisible)
++{
++    const SmallRect windowRect = info.windowRect();
++
++    const SmallRect scrapeRect(
++        windowRect.left(), windowRect.top(),
++        std::min<SHORT>(std::min(windowRect.width(), m_ptySize.X),
++                        MAX_CONSOLE_WIDTH),
++        std::min<SHORT>(std::min(windowRect.height(), m_ptySize.Y),
++                        BUFFER_LINE_COUNT));
++    const int w = scrapeRect.width();
++    const int h = scrapeRect.height();
++
++    const Coord cursor = info.cursorPosition();
++    const bool showTerminalCursor =
++        consoleCursorVisible && scrapeRect.contains(cursor);
++    const int cursorColumn = !showTerminalCursor ? -1 : cursor.X - scrapeRect.Left;
++    const int cursorLine = !showTerminalCursor ? -1 : cursor.Y - scrapeRect.Top;
++
++    if (!showTerminalCursor) {
++        m_terminal->hideTerminalCursor();
++    }
++
++    largeConsoleRead(m_readBuffer, *m_consoleBuffer, scrapeRect, attributesMask());
++
++    for (int line = 0; line < h; ++line) {
++        const CHAR_INFO *const curLine =
++            m_readBuffer.lineData(scrapeRect.top() + line);
++        ConsoleLine &bufLine = m_bufferData[line];
++        if (bufLine.detectChangeAndSetLine(curLine, w)) {
++            const int lineCursorColumn =
++                line == cursorLine ? cursorColumn : -1;
++            m_terminal->sendLine(line, curLine, w, lineCursorColumn);
++        }
++    }
++
++    if (showTerminalCursor) {
++        m_terminal->showTerminalCursor(cursorColumn, cursorLine);
++    }
++}
++
++bool Scraper::scrollingScrapeOutput(const ConsoleScreenBufferInfo &info,
++                                    bool consoleCursorVisible,
++                                    bool tentative)
++{
++    const Coord cursor = info.cursorPosition();
++    const SmallRect windowRect = info.windowRect();
++
++    if (m_syncRow != -1) {
++        // If a synchronizing marker was placed into the history, look for it
++        // and adjust the scroll count.
++        const int markerRow = findSyncMarker();
++        if (markerRow == -1) {
++            if (tentative) {
++                // I *think* it's possible to keep going, but it's simple to
++                // bail out.
++                return false;
++            }
++            // Something has happened.  Reset the terminal.
++            trace("Sync marker has disappeared -- resetting the terminal"
++                  " (m_syncCounter=%u)",
++                  m_syncCounter);
++            resetConsoleTracking(Terminal::SendClear, windowRect.top());
++        } else if (markerRow != m_syncRow) {
++            ASSERT(markerRow < m_syncRow);
++            m_scrolledCount += (m_syncRow - markerRow);
++            m_syncRow = markerRow;
++            // If the buffer has scrolled, then the entire window is dirty.
++            markEntireWindowDirty(windowRect);
++        }
++    }
++
++    // Creating a new sync row requires clearing part of the console buffer, so
++    // avoid doing it if there's already a sync row that's good enough.
++    const int newSyncRow =
++        static_cast<int>(windowRect.top()) - SYNC_MARKER_LEN - SYNC_MARKER_MARGIN;
++    const bool shouldCreateSyncRow =
++        newSyncRow >= m_syncRow + SYNC_MARKER_LEN + SYNC_MARKER_MARGIN;
++    if (tentative && shouldCreateSyncRow) {
++        // It's difficult even in principle to put down a new marker if the
++        // console can scroll an arbitrarily amount while we're writing.
++        return false;
++    }
++
++    // Update the dirty line count:
++    //  - If the window has moved, the entire window is dirty.
++    //  - Everything up to the cursor is dirty.
++    //  - All lines above the window are dirty.
++    //  - Any non-blank lines are dirty.
++    if (m_dirtyWindowTop != -1) {
++        if (windowRect.top() > m_dirtyWindowTop) {
++            // The window has moved down, presumably as a result of scrolling.
++            markEntireWindowDirty(windowRect);
++        } else if (windowRect.top() < m_dirtyWindowTop) {
++            if (tentative) {
++                // I *think* it's possible to keep going, but it's simple to
++                // bail out.
++                return false;
++            }
++            // The window has moved upward.  This is generally not expected to
++            // happen, but the CMD/PowerShell CLS command will move the window
++            // to the top as part of clearing everything else in the console.
++            trace("Window moved upward -- resetting the terminal"
++                  " (m_syncCounter=%u)",
++                  m_syncCounter);
++            resetConsoleTracking(Terminal::SendClear, windowRect.top());
++        }
++    }
++    m_dirtyWindowTop = windowRect.top();
++    m_dirtyLineCount = std::max(m_dirtyLineCount, cursor.Y + 1);
++    m_dirtyLineCount = std::max(m_dirtyLineCount, (int)windowRect.top());
++
++    // There will be at least one dirty line, because there is a cursor.
++    ASSERT(m_dirtyLineCount >= 1);
++
++    // The first line to scrape, in virtual line coordinates.
++    const int64_t firstVirtLine = std::min(m_scrapedLineCount,
++                                           windowRect.top() + m_scrolledCount);
++
++    // Read all the data we will need from the console.  Start reading with the
++    // first line to scrape, but adjust the the read area upward to account for
++    // scanForDirtyLines' need to read the previous attribute.  Read to the
++    // bottom of the window.  (It's not clear to me whether the
++    // m_dirtyLineCount adjustment here is strictly necessary.  It isn't
++    // necessary so long as the cursor is inside the current window.)
++    const int firstReadLine = std::min<int>(firstVirtLine - m_scrolledCount,
++                                            m_dirtyLineCount - 1);
++    const int stopReadLine = std::max(windowRect.top() + windowRect.height(),
++                                      m_dirtyLineCount);
++    ASSERT(firstReadLine >= 0 && stopReadLine > firstReadLine);
++    largeConsoleRead(m_readBuffer,
++                     *m_consoleBuffer,
++                     SmallRect(0, firstReadLine,
++                               std::min<SHORT>(info.bufferSize().X,
++                                               MAX_CONSOLE_WIDTH),
++                               stopReadLine - firstReadLine),
++                     attributesMask());
++
++    // If we're scraping the buffer without freezing it, we have to query the
++    // buffer position data separately from the buffer content, so the two
++    // could easily be out-of-sync.  If they *are* out-of-sync, abort the
++    // scrape operation and restart it frozen.  (We may have updated the
++    // dirty-line high-water-mark, but that should be OK.)
++    if (tentative) {
++        const auto infoCheck = m_consoleBuffer->bufferInfo();
++        if (info.bufferSize() != infoCheck.bufferSize() ||
++                info.windowRect() != infoCheck.windowRect() ||
++                info.cursorPosition() != infoCheck.cursorPosition()) {
++            return false;
++        }
++        if (m_syncRow != -1 && m_syncRow != findSyncMarker()) {
++            return false;
++        }
++    }
++
++    if (shouldCreateSyncRow) {
++        ASSERT(!tentative);
++        createSyncMarker(newSyncRow);
++    }
++
++    // At this point, we're finished interacting (reading or writing) the
++    // console, and we just need to convert our collected data into terminal
++    // output.
++
++    scanForDirtyLines(windowRect);
++
++    // Note that it's possible for all the lines on the current window to
++    // be non-dirty.
++
++    // The line to stop scraping at, in virtual line coordinates.
++    const int64_t stopVirtLine =
++        std::min(m_dirtyLineCount, windowRect.top() + windowRect.height()) +
++            m_scrolledCount;
++
++    const bool showTerminalCursor =
++        consoleCursorVisible && windowRect.contains(cursor);
++    const int64_t cursorLine = !showTerminalCursor ? -1 : cursor.Y + m_scrolledCount;
++    const int cursorColumn = !showTerminalCursor ? -1 : cursor.X;
++
++    if (!showTerminalCursor) {
++        m_terminal->hideTerminalCursor();
++    }
++
++    bool sawModifiedLine = false;
++
++    const int w = m_readBuffer.rect().width();
++    for (int64_t line = firstVirtLine; line < stopVirtLine; ++line) {
++        const CHAR_INFO *curLine =
++            m_readBuffer.lineData(line - m_scrolledCount);
++        ConsoleLine &bufLine = m_bufferData[line % BUFFER_LINE_COUNT];
++        if (line > m_maxBufferedLine) {
++            m_maxBufferedLine = line;
++            sawModifiedLine = true;
++        }
++        if (sawModifiedLine) {
++            bufLine.setLine(curLine, w);
++        } else {
++            sawModifiedLine = bufLine.detectChangeAndSetLine(curLine, w);
++        }
++        if (sawModifiedLine) {
++            const int lineCursorColumn =
++                line == cursorLine ? cursorColumn : -1;
++            m_terminal->sendLine(line, curLine, w, lineCursorColumn);
++        }
++    }
++
++    m_scrapedLineCount = windowRect.top() + m_scrolledCount;
++
++    if (showTerminalCursor) {
++        m_terminal->showTerminalCursor(cursorColumn, cursorLine);
++    }
++
++    return true;
++}
++
++void Scraper::syncMarkerText(CHAR_INFO (&output)[SYNC_MARKER_LEN])
++{
++    // XXX: The marker text generated here could easily collide with ordinary
++    // console output.  Does it make sense to try to avoid the collision?
++    char str[SYNC_MARKER_LEN + 1];
++    winpty_snprintf(str, "S*Y*N*C*%08x", m_syncCounter);
++    for (int i = 0; i < SYNC_MARKER_LEN; ++i) {
++        output[i].Char.UnicodeChar = str[i];
++        output[i].Attributes = 7;
++    }
++}
++
++int Scraper::findSyncMarker()
++{
++    ASSERT(m_syncRow >= 0);
++    CHAR_INFO marker[SYNC_MARKER_LEN];
++    CHAR_INFO column[BUFFER_LINE_COUNT];
++    syncMarkerText(marker);
++    SmallRect rect(0, 0, 1, m_syncRow + SYNC_MARKER_LEN);
++    m_consoleBuffer->read(rect, column);
++    int i;
++    for (i = m_syncRow; i >= 0; --i) {
++        int j;
++        for (j = 0; j < SYNC_MARKER_LEN; ++j) {
++            if (column[i + j].Char.UnicodeChar != marker[j].Char.UnicodeChar)
++                break;
++        }
++        if (j == SYNC_MARKER_LEN)
++            return i;
++    }
++    return -1;
++}
++
++void Scraper::createSyncMarker(int row)
++{
++    ASSERT(row >= 1);
++
++    // Clear the lines around the marker to ensure that Windows 10's rewrapping
++    // does not affect the marker.
++    m_consoleBuffer->clearLines(row - 1, SYNC_MARKER_LEN + 1,
++                                m_consoleBuffer->bufferInfo());
++
++    // Write a new marker.
++    m_syncCounter++;
++    CHAR_INFO marker[SYNC_MARKER_LEN];
++    syncMarkerText(marker);
++    m_syncRow = row;
++    SmallRect markerRect(0, m_syncRow, 1, SYNC_MARKER_LEN);
++    m_consoleBuffer->write(markerRect, marker);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9c10d80aedc3990cdf2395100ca3c55c909674e2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,103 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_SCRAPER_H
++#define AGENT_SCRAPER_H
++
++#include <windows.h>
++
++#include <stdint.h>
++
++#include <memory>
++#include <vector>
++
++#include "ConsoleLine.h"
++#include "Coord.h"
++#include "LargeConsoleRead.h"
++#include "SmallRect.h"
++#include "Terminal.h"
++
++class ConsoleScreenBufferInfo;
++class Win32Console;
++class Win32ConsoleBuffer;
++
++// We must be able to issue a single ReadConsoleOutputW call of
++// MAX_CONSOLE_WIDTH characters, and a single read of approximately several
++// hundred fewer characters than BUFFER_LINE_COUNT.
++const int BUFFER_LINE_COUNT = 3000;
++const int MAX_CONSOLE_WIDTH = 2500;
++const int MAX_CONSOLE_HEIGHT = 2000;
++const int SYNC_MARKER_LEN = 16;
++const int SYNC_MARKER_MARGIN = 200;
++
++class Scraper {
++public:
++    Scraper(
++        Win32Console &console,
++        Win32ConsoleBuffer &buffer,
++        std::unique_ptr<Terminal> terminal,
++        Coord initialSize);
++    ~Scraper();
++    void resizeWindow(Win32ConsoleBuffer &buffer,
++                      Coord newSize,
++                      ConsoleScreenBufferInfo &finalInfoOut);
++    void scrapeBuffer(Win32ConsoleBuffer &buffer,
++                      ConsoleScreenBufferInfo &finalInfoOut);
++    Terminal &terminal() { return *m_terminal; }
++
++private:
++    void resetConsoleTracking(
++        Terminal::SendClearFlag sendClear, int64_t scrapedLineCount);
++    void markEntireWindowDirty(const SmallRect &windowRect);
++    void scanForDirtyLines(const SmallRect &windowRect);
++    void clearBufferLines(int firstRow, int count);
++    void resizeImpl(const ConsoleScreenBufferInfo &origInfo);
++    void syncConsoleContentAndSize(bool forceResize,
++                                   ConsoleScreenBufferInfo &finalInfoOut);
++    WORD attributesMask();
++    void directScrapeOutput(const ConsoleScreenBufferInfo &info,
++                            bool consoleCursorVisible);
++    bool scrollingScrapeOutput(const ConsoleScreenBufferInfo &info,
++                               bool consoleCursorVisible,
++                               bool tentative);
++    void syncMarkerText(CHAR_INFO (&output)[SYNC_MARKER_LEN]);
++    int findSyncMarker();
++    void createSyncMarker(int row);
++
++private:
++    Win32Console &m_console;
++    Win32ConsoleBuffer *m_consoleBuffer = nullptr;
++    std::unique_ptr<Terminal> m_terminal;
++
++    int m_syncRow = -1;
++    unsigned int m_syncCounter = 0;
++
++    bool m_directMode = false;
++    Coord m_ptySize;
++    int64_t m_scrapedLineCount = 0;
++    int64_t m_scrolledCount = 0;
++    int64_t m_maxBufferedLine = -1;
++    LargeConsoleReadBuffer m_readBuffer;
++    std::vector<ConsoleLine> m_bufferData;
++    int m_dirtyWindowTop = -1;
++    int m_dirtyLineCount = 0;
++};
++
++#endif // AGENT_SCRAPER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..41ff94a90de0ff54086a487d3002501a4b22a606
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,75 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef SIMPLE_POOL_H
++#define SIMPLE_POOL_H
++
++#include <stdlib.h>
++
++#include <vector>
++
++#include "../shared/WinptyAssert.h"
++
++template <typename T, size_t chunkSize>
++class SimplePool {
++public:
++    ~SimplePool();
++    T *alloc();
++    void clear();
++private:
++    struct Chunk {
++        size_t count;
++        T *data;
++    };
++    std::vector<Chunk> m_chunks;
++};
++
++template <typename T, size_t chunkSize>
++SimplePool<T, chunkSize>::~SimplePool() {
++    clear();
++}
++
++template <typename T, size_t chunkSize>
++void SimplePool<T, chunkSize>::clear() {
++    for (size_t ci = 0; ci < m_chunks.size(); ++ci) {
++        Chunk &chunk = m_chunks[ci];
++        for (size_t ti = 0; ti < chunk.count; ++ti) {
++            chunk.data[ti].~T();
++        }
++        free(chunk.data);
++    }
++    m_chunks.clear();
++}
++
++template <typename T, size_t chunkSize>
++T *SimplePool<T, chunkSize>::alloc() {
++    if (m_chunks.empty() || m_chunks.back().count == chunkSize) {
++        T *newData = reinterpret_cast<T*>(malloc(sizeof(T) * chunkSize));
++        ASSERT(newData != NULL);
++        Chunk newChunk = { 0, newData };
++        m_chunks.push_back(newChunk);
++    }
++    Chunk &chunk = m_chunks.back();
++    T *ret = &chunk.data[chunk.count++];
++    new (ret) T();
++    return ret;
++}
++
++#endif // SIMPLE_POOL_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..bad0b88683ad88e106cc7e5e954b1648a9635f3a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,143 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef SMALLRECT_H
++#define SMALLRECT_H
++
++#include <windows.h>
++
++#include <algorithm>
++#include <string>
++
++#include "../shared/winpty_snprintf.h"
++#include "Coord.h"
++
++struct SmallRect : SMALL_RECT
++{
++    SmallRect()
++    {
++        Left = Right = Top = Bottom = 0;
++    }
++
++    SmallRect(SHORT x, SHORT y, SHORT width, SHORT height)
++    {
++        Left = x;
++        Top = y;
++        Right = x + width - 1;
++        Bottom = y + height - 1;
++    }
++
++    SmallRect(const COORD &topLeft, const COORD &size)
++    {
++        Left = topLeft.X;
++        Top = topLeft.Y;
++        Right = Left + size.X - 1;
++        Bottom = Top + size.Y - 1;
++    }
++
++    SmallRect(const SMALL_RECT &other)
++    {
++        *(SMALL_RECT*)this = other;
++    }
++
++    SmallRect(const SmallRect &other)
++    {
++        *(SMALL_RECT*)this = *(const SMALL_RECT*)&other;
++    }
++
++    SmallRect &operator=(const SmallRect &other)
++    {
++        *(SMALL_RECT*)this = *(const SMALL_RECT*)&other;
++        return *this;
++    }
++
++    bool contains(const SmallRect &other) const
++    {
++        return other.Left >= Left &&
++               other.Right <= Right &&
++               other.Top >= Top &&
++               other.Bottom <= Bottom;
++    }
++
++    bool contains(const Coord &other) const
++    {
++        return other.X >= Left &&
++               other.X <= Right &&
++               other.Y >= Top &&
++               other.Y <= Bottom;
++    }
++
++    SmallRect intersected(const SmallRect &other) const
++    {
++        int x1 = std::max(Left, other.Left);
++        int x2 = std::min(Right, other.Right);
++        int y1 = std::max(Top, other.Top);
++        int y2 = std::min(Bottom, other.Bottom);
++        return SmallRect(x1,
++                         y1,
++                         std::max(0, x2 - x1 + 1),
++                         std::max(0, y2 - y1 + 1));
++    }
++
++    SmallRect ensureLineIncluded(SHORT line) const
++    {
++        const SHORT h = height();
++        if (line < Top) {
++            return SmallRect(Left, line, width(), h);
++        } else if (line > Bottom) {
++            return SmallRect(Left, line - h + 1, width(), h);
++        } else {
++            return *this;
++        }
++    }
++
++    SHORT top() const               { return Top;                       }
++    SHORT left() const              { return Left;                      }
++    SHORT width() const             { return Right - Left + 1;          }
++    SHORT height() const            { return Bottom - Top + 1;          }
++    void setTop(SHORT top)          { Top = top;                        }
++    void setLeft(SHORT left)        { Left = left;                      }
++    void setWidth(SHORT width)      { Right = Left + width - 1;         }
++    void setHeight(SHORT height)    { Bottom = Top + height - 1;        }
++    Coord size() const              { return Coord(width(), height());  }
++
++    bool operator==(const SmallRect &other) const
++    {
++        return Left == other.Left &&
++               Right == other.Right &&
++               Top == other.Top &&
++               Bottom == other.Bottom;
++    }
++
++    bool operator!=(const SmallRect &other) const
++    {
++        return !(*this == other);
++    }
++
++    std::string toString() const
++    {
++        char ret[64];
++        winpty_snprintf(ret, "(x=%d,y=%d,w=%d,h=%d)",
++                        Left, Top, width(), height());
++        return std::string(ret);
++    }
++};
++
++#endif // SMALLRECT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..afa0a362600b5159ab33790090ebd586b76fca2c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,535 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Terminal.h"
++
++#include <windows.h>
++#include <stdio.h>
++#include <string.h>
++
++#include <string>
++
++#include "NamedPipe.h"
++#include "UnicodeEncoding.h"
++#include "../shared/DebugClient.h"
++#include "../shared/WinptyAssert.h"
++#include "../shared/winpty_snprintf.h"
++
++#define CSI "\x1b["
++
++// Work around the old MinGW, which lacks COMMON_LVB_LEADING_BYTE and
++// COMMON_LVB_TRAILING_BYTE.
++const int WINPTY_COMMON_LVB_LEADING_BYTE  = 0x100;
++const int WINPTY_COMMON_LVB_TRAILING_BYTE = 0x200;
++const int WINPTY_COMMON_LVB_REVERSE_VIDEO = 0x4000;
++const int WINPTY_COMMON_LVB_UNDERSCORE    = 0x8000;
++
++const int COLOR_ATTRIBUTE_MASK =
++        FOREGROUND_BLUE |
++        FOREGROUND_GREEN |
++        FOREGROUND_RED |
++        FOREGROUND_INTENSITY |
++        BACKGROUND_BLUE |
++        BACKGROUND_GREEN |
++        BACKGROUND_RED |
++        BACKGROUND_INTENSITY |
++        WINPTY_COMMON_LVB_REVERSE_VIDEO |
++        WINPTY_COMMON_LVB_UNDERSCORE;
++
++const int FLAG_RED    = 1;
++const int FLAG_GREEN  = 2;
++const int FLAG_BLUE   = 4;
++const int FLAG_BRIGHT = 8;
++
++const int BLACK  = 0;
++const int DKGRAY = BLACK | FLAG_BRIGHT;
++const int LTGRAY = FLAG_RED | FLAG_GREEN | FLAG_BLUE;
++const int WHITE  = LTGRAY | FLAG_BRIGHT;
++
++// SGR parameters (Select Graphic Rendition)
++const int SGR_FORE = 30;
++const int SGR_FORE_HI = 90;
++const int SGR_BACK = 40;
++const int SGR_BACK_HI = 100;
++
++namespace {
++
++static void outUInt(std::string &out, unsigned int n)
++{
++    char buf[32];
++    char *pbuf = &buf[32];
++    *(--pbuf) = '\0';
++    do {
++        *(--pbuf) = '0' + n % 10;
++        n /= 10;
++    } while (n != 0);
++    out.append(pbuf);
++}
++
++static void outputSetColorSgrParams(std::string &out, bool isFore, int color)
++{
++    out.push_back(';');
++    const int sgrBase = isFore ? SGR_FORE : SGR_BACK;
++    if (color & FLAG_BRIGHT) {
++        // Some terminals don't support the 9X/10X "intensive" color parameters
++        // (e.g. the Eclipse TM terminal as of this writing).  Those terminals
++        // will quietly ignore a 9X/10X code, and the other terminals will
++        // ignore a 3X/4X code if it's followed by a 9X/10X code.  Therefore,
++        // output a 3X/4X code as a fallback, then override it.
++        const int colorBase = color & ~FLAG_BRIGHT;
++        outUInt(out, sgrBase + colorBase);
++        out.push_back(';');
++        outUInt(out, sgrBase + (SGR_FORE_HI - SGR_FORE) + colorBase);
++    } else {
++        outUInt(out, sgrBase + color);
++    }
++}
++
++static void outputSetColor(std::string &out, int color)
++{
++    int fore = 0;
++    int back = 0;
++    if (color & FOREGROUND_RED)       fore |= FLAG_RED;
++    if (color & FOREGROUND_GREEN)     fore |= FLAG_GREEN;
++    if (color & FOREGROUND_BLUE)      fore |= FLAG_BLUE;
++    if (color & FOREGROUND_INTENSITY) fore |= FLAG_BRIGHT;
++    if (color & BACKGROUND_RED)       back |= FLAG_RED;
++    if (color & BACKGROUND_GREEN)     back |= FLAG_GREEN;
++    if (color & BACKGROUND_BLUE)      back |= FLAG_BLUE;
++    if (color & BACKGROUND_INTENSITY) back |= FLAG_BRIGHT;
++
++    if (color & WINPTY_COMMON_LVB_REVERSE_VIDEO) {
++        // n.b.: The COMMON_LVB_REVERSE_VIDEO flag also swaps
++        // FOREGROUND_INTENSITY and BACKGROUND_INTENSITY.  Tested on
++        // Windows 10 v14393.
++        std::swap(fore, back);
++    }
++
++    // Translate the fore/back colors into terminal escape codes using
++    // a heuristic that works OK with common white-on-black or
++    // black-on-white color schemes.  We don't know which color scheme
++    // the terminal is using.  It is ugly to force white-on-black text
++    // on a black-on-white terminal, and it's even ugly to force the
++    // matching scheme.  It's probably relevant that the default
++    // fore/back terminal colors frequently do not match any of the 16
++    // palette colors.
++
++    // Typical default terminal color schemes (according to palette,
++    // when possible):
++    //  - mintty:               LtGray-on-Black(A)
++    //  - putty:                LtGray-on-Black(A)
++    //  - xterm:                LtGray-on-Black(A)
++    //  - Konsole:              LtGray-on-Black(A)
++    //  - JediTerm/JetBrains:   Black-on-White(B)
++    //  - rxvt:                 Black-on-White(B)
++
++    // If the background is the default color (black), then it will
++    // map to Black(A) or White(B).  If we translate White to White,
++    // then a Black background and a White background in the console
++    // are both White with (B).  Therefore, we should translate White
++    // using SGR 7 (Invert).  The typical finished mapping table for
++    // background grayscale colors is:
++    //
++    //  (A) White => LtGray(fore)
++    //  (A) Black => Black(back)
++    //  (A) LtGray => LtGray
++    //  (A) DkGray => DkGray
++    //
++    //  (B) White => Black(fore)
++    //  (B) Black => White(back)
++    //  (B) LtGray => LtGray
++    //  (B) DkGray => DkGray
++    //
++
++    out.append(CSI "0");
++    if (back == BLACK) {
++        if (fore == LTGRAY) {
++            // The "default" foreground color.  Use the terminal's
++            // default colors.
++        } else if (fore == WHITE) {
++            // Sending the literal color white would behave poorly if
++            // the terminal were black-on-white.  Sending Bold is not
++            // guaranteed to alter the color, but it will make the text
++            // visually distinct, so do that instead.
++            out.append(";1");
++        } else if (fore == DKGRAY) {
++            // Set the foreground color to DkGray(90) with a fallback
++            // of LtGray(37) for terminals that don't handle the 9X SGR
++            // parameters (e.g. Eclipse's TM Terminal as of this
++            // writing).
++            out.append(";37;90");
++        } else {
++            outputSetColorSgrParams(out, true, fore);
++        }
++    } else if (back == WHITE) {
++        // Set the background color using Invert on the default
++        // foreground color, and set the foreground color by setting a
++        // background color.
++
++        // Use the terminal's inverted colors.
++        out.append(";7");
++        if (fore == LTGRAY || fore == BLACK) {
++            // We're likely mapping Console White to terminal LtGray or
++            // Black.  If they are the Console foreground color, then
++            // don't set a terminal foreground color to avoid creating
++            // invisible text.
++        } else {
++            outputSetColorSgrParams(out, false, fore);
++        }
++    } else {
++        // Set the foreground and background to match exactly that in
++        // the Windows console.
++        outputSetColorSgrParams(out, true, fore);
++        outputSetColorSgrParams(out, false, back);
++    }
++    if (fore == back) {
++        // The foreground and background colors are exactly equal, so
++        // attempt to hide the text using the Conceal SGR parameter,
++        // which some terminals support.
++        out.append(";8");
++    }
++    if (color & WINPTY_COMMON_LVB_UNDERSCORE) {
++        out.append(";4");
++    }
++    out.push_back('m');
++}
++
++static inline unsigned int fixSpecialCharacters(unsigned int ch)
++{
++    if (ch <= 0x1b) {
++        switch (ch) {
++            // The Windows Console has a popup window (e.g. that appears with
++            // F7) that is sometimes bordered with box-drawing characters.
++            // With the Japanese and Korean system locales (CP932 and CP949),
++            // the UnicodeChar values for the box-drawing characters are 1
++            // through 6.  Detect this and map the values to the correct
++            // Unicode values.
++            //
++            // N.B. In the English locale, the UnicodeChar values are correct,
++            // and they identify single-line characters rather than
++            // double-line.  In the Chinese Simplified and Traditional locales,
++            // the popups use ASCII characters instead.
++            case 1: return 0x2554; // BOX DRAWINGS DOUBLE DOWN AND RIGHT
++            case 2: return 0x2557; // BOX DRAWINGS DOUBLE DOWN AND LEFT
++            case 3: return 0x255A; // BOX DRAWINGS DOUBLE UP AND RIGHT
++            case 4: return 0x255D; // BOX DRAWINGS DOUBLE UP AND LEFT
++            case 5: return 0x2551; // BOX DRAWINGS DOUBLE VERTICAL
++            case 6: return 0x2550; // BOX DRAWINGS DOUBLE HORIZONTAL
++
++            // Convert an escape character to some other character.  This
++            // conversion only applies to console cells containing an escape
++            // character.  In newer versions of Windows 10 (e.g. 10.0.10586),
++            // the non-legacy console recognizes escape sequences in
++            // WriteConsole and interprets them without writing them to the
++            // cells of the screen buffer.  In that case, the conversion here
++            // does not apply.
++            case 0x1b: return '?';
++        }
++    }
++    return ch;
++}
++
++static inline bool isFullWidthCharacter(const CHAR_INFO *data, int width)
++{
++    if (width < 2) {
++        return false;
++    }
++    return
++        (data[0].Attributes & WINPTY_COMMON_LVB_LEADING_BYTE) &&
++        (data[1].Attributes & WINPTY_COMMON_LVB_TRAILING_BYTE) &&
++        data[0].Char.UnicodeChar == data[1].Char.UnicodeChar;
++}
++
++// Scan to find a single Unicode Scalar Value.  Full-width characters occupy
++// two console cells, and this code also tries to handle UTF-16 surrogate
++// pairs.
++//
++// Windows expands at least some wide characters outside the Basic
++// Multilingual Plane into four cells, such as U+20000:
++//   1. 0xD840, attr=0x107
++//   2. 0xD840, attr=0x207
++//   3. 0xDC00, attr=0x107
++//   4. 0xDC00, attr=0x207
++// Even in the Traditional Chinese locale on Windows 10, this text is rendered
++// as two boxes, but if those boxes are copied-and-pasted, the character is
++// copied correctly.
++static inline void scanUnicodeScalarValue(
++    const CHAR_INFO *data, int width,
++    int &outCellCount, unsigned int &outCharValue)
++{
++    ASSERT(width >= 1);
++
++    const int w1 = isFullWidthCharacter(data, width) ? 2 : 1;
++    const wchar_t c1 = data[0].Char.UnicodeChar;
++
++    if ((c1 & 0xF800) == 0xD800) {
++        // The first cell is either a leading or trailing surrogate pair.
++        if ((c1 & 0xFC00) != 0xD800 ||
++                width <= w1 ||
++                ((data[w1].Char.UnicodeChar & 0xFC00) != 0xDC00)) {
++            // Invalid surrogate pair
++            outCellCount = w1;
++            outCharValue = '?';
++        } else {
++            // Valid surrogate pair
++            outCellCount = w1 + (isFullWidthCharacter(&data[w1], width - w1) ? 2 : 1);
++            outCharValue = decodeSurrogatePair(c1, data[w1].Char.UnicodeChar);
++        }
++    } else {
++        outCellCount = w1;
++        outCharValue = c1;
++    }
++}
++
++} // anonymous namespace
++
++void Terminal::reset(SendClearFlag sendClearFirst, int64_t newLine)
++{
++    if (sendClearFirst == SendClear && !m_plainMode) {
++        // 0m   ==> reset SGR parameters
++        // 1;1H ==> move cursor to top-left position
++        // 2J   ==> clear the entire screen
++        m_output.write(CSI "0m" CSI "1;1H" CSI "2J");
++    }
++    m_remoteLine = newLine;
++    m_remoteColumn = 0;
++    m_lineData.clear();
++    m_cursorHidden = false;
++    m_remoteColor = -1;
++}
++
++void Terminal::sendLine(int64_t line, const CHAR_INFO *lineData, int width,
++                        int cursorColumn)
++{
++    ASSERT(width >= 1);
++
++    moveTerminalToLine(line);
++
++    // If possible, see if we can append to what we've already output for this
++    // line.
++    if (m_lineDataValid) {
++        ASSERT(m_lineData.size() == static_cast<size_t>(m_remoteColumn));
++        if (m_remoteColumn > 0) {
++            // In normal mode, if m_lineData.size() equals `width`, then we
++            // will have trouble outputing the "erase rest of line" command,
++            // which must be output before reaching the end of the line.  In
++            // plain mode, we don't output that command, so we're OK with a
++            // full line.
++            bool okWidth = false;
++            if (m_plainMode) {
++                okWidth = static_cast<size_t>(width) >= m_lineData.size();
++            } else {
++                okWidth = static_cast<size_t>(width) > m_lineData.size();
++            }
++            if (!okWidth ||
++                    memcmp(m_lineData.data(), lineData,
++                           sizeof(CHAR_INFO) * m_lineData.size()) != 0) {
++                m_lineDataValid = false;
++            }
++        }
++    }
++    if (!m_lineDataValid) {
++        // We can't reuse, so we must reset this line.
++        hideTerminalCursor();
++        if (m_plainMode) {
++            // We can't backtrack, so repeat this line.
++            m_output.write("\r\n");
++        } else {
++            m_output.write("\r");
++        }
++        m_lineDataValid = true;
++        m_lineData.clear();
++        m_remoteColumn = 0;
++    }
++
++    std::string &termLine = m_termLineWorkingBuffer;
++    termLine.clear();
++    size_t trimmedLineLength = 0;
++    int trimmedCellCount = m_lineData.size();
++    bool alreadyErasedLine = false;
++
++    int cellCount = 1;
++    for (int i = m_lineData.size(); i < width; i += cellCount) {
++        if (m_outputColor) {
++            int color = lineData[i].Attributes & COLOR_ATTRIBUTE_MASK;
++            if (color != m_remoteColor) {
++                outputSetColor(termLine, color);
++                trimmedLineLength = termLine.size();
++                m_remoteColor = color;
++
++                // All the cells just up to this color change will be output.
++                trimmedCellCount = i;
++            }
++        }
++        unsigned int ch;
++        scanUnicodeScalarValue(&lineData[i], width - i, cellCount, ch);
++        if (ch == ' ') {
++            // Tentatively add this space character.  We'll only output it if
++            // we see something interesting after it.
++            termLine.push_back(' ');
++        } else {
++            if (i + cellCount == width) {
++                // We'd like to erase the line after outputting all non-blank
++                // characters, but this doesn't work if the last cell in the
++                // line is non-blank.  At the point, the cursor is positioned
++                // just past the end of the line, but in many terminals,
++                // issuing a CSI 0K at that point also erases the last cell in
++                // the line.  Work around this behavior by issuing the erase
++                // one character early in that case.
++                if (!m_plainMode) {
++                    termLine.append(CSI "0K"); // Erase from cursor to EOL
++                }
++                alreadyErasedLine = true;
++            }
++            ch = fixSpecialCharacters(ch);
++            char enc[4];
++            int enclen = encodeUtf8(enc, ch);
++            if (enclen == 0) {
++                enc[0] = '?';
++                enclen = 1;
++            }
++            termLine.append(enc, enclen);
++            trimmedLineLength = termLine.size();
++
++            // All the cells up to and including this cell will be output.
++            trimmedCellCount = i + cellCount;
++        }
++    }
++
++    if (cursorColumn != -1 && trimmedCellCount > cursorColumn) {
++        // The line content would run past the cursor, so hide it before we
++        // output.
++        hideTerminalCursor();
++    }
++
++    m_output.write(termLine.data(), trimmedLineLength);
++    if (!alreadyErasedLine && !m_plainMode) {
++        m_output.write(CSI "0K"); // Erase from cursor to EOL
++    }
++
++    ASSERT(trimmedCellCount <= width);
++    m_lineData.insert(m_lineData.end(),
++                      &lineData[m_lineData.size()],
++                      &lineData[trimmedCellCount]);
++    m_remoteColumn = trimmedCellCount;
++}
++
++void Terminal::showTerminalCursor(int column, int64_t line)
++{
++    moveTerminalToLine(line);
++    if (!m_plainMode) {
++        if (m_remoteColumn != column) {
++            char buffer[32];
++            winpty_snprintf(buffer, CSI "%dG", column + 1);
++            m_output.write(buffer);
++            m_lineDataValid = (column == 0);
++            m_lineData.clear();
++            m_remoteColumn = column;
++        }
++        if (m_cursorHidden) {
++            m_output.write(CSI "?25h");
++            m_cursorHidden = false;
++        }
++    }
++}
++
++void Terminal::hideTerminalCursor()
++{
++    if (!m_plainMode) {
++        if (m_cursorHidden) {
++            return;
++        }
++        m_output.write(CSI "?25l");
++        m_cursorHidden = true;
++    }
++}
++
++void Terminal::moveTerminalToLine(int64_t line)
++{
++    if (line == m_remoteLine) {
++        return;
++    }
++
++    // Do not use CPL or CNL.  Konsole 2.5.4 does not support Cursor Previous
++    // Line (CPL) -- there are "Undecodable sequence" errors.  gnome-terminal
++    // 2.32.0 does handle it.  Cursor Next Line (CNL) does nothing if the
++    // cursor is on the last line already.
++
++    hideTerminalCursor();
++
++    if (line < m_remoteLine) {
++        if (m_plainMode) {
++            // We can't backtrack, so instead repeat the lines again.
++            m_output.write("\r\n");
++            m_remoteLine = line;
++        } else {
++            // Backtrack and overwrite previous lines.
++            // CUrsor Up (CUU)
++            char buffer[32];
++            winpty_snprintf(buffer, "\r" CSI "%uA",
++                static_cast<unsigned int>(m_remoteLine - line));
++            m_output.write(buffer);
++            m_remoteLine = line;
++        }
++    } else if (line > m_remoteLine) {
++        while (line > m_remoteLine) {
++            m_output.write("\r\n");
++            m_remoteLine++;
++        }
++    }
++
++    m_lineDataValid = true;
++    m_lineData.clear();
++    m_remoteColumn = 0;
++}
++
++void Terminal::enableMouseMode(bool enabled)
++{
++    if (m_mouseModeEnabled == enabled || m_plainMode) {
++        return;
++    }
++    m_mouseModeEnabled = enabled;
++    if (enabled) {
++        // Start by disabling UTF-8 coordinate mode (1005), just in case we
++        // have a terminal that does not support 1006/1015 modes, and 1005
++        // happens to be enabled.  The UTF-8 coordinates can't be unambiguously
++        // decoded.
++        //
++        // Enable basic mouse support first (1000), then try to switch to
++        // button-move mode (1002), then try full mouse-move mode (1003).
++        // Terminals that don't support a mode will be stuck at the highest
++        // mode they do support.
++        //
++        // Enable encoding mode 1015 first, then try to switch to 1006.  On
++        // some terminals, both modes will be enabled, but 1006 will have
++        // priority.  On other terminals, 1006 wins because it's listed last.
++        //
++        // See misc/MouseInputNotes.txt for details.
++        m_output.write(
++            CSI "?1005l"
++            CSI "?1000h" CSI "?1002h" CSI "?1003h" CSI "?1015h" CSI "?1006h");
++    } else {
++        // Resetting both encoding modes (1006 and 1015) is necessary, but
++        // apparently we only need to use reset on one of the 100[023] modes.
++        // Doing both doesn't hurt.
++        m_output.write(
++            CSI "?1006l" CSI "?1015l" CSI "?1003l" CSI "?1002l" CSI "?1000l");
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..058eb2650e7232bbc03985a6d1a1191ec0737860
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,69 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef TERMINAL_H
++#define TERMINAL_H
++
++#include <windows.h>
++#include <stdint.h>
++
++#include <string>
++#include <vector>
++
++#include "Coord.h"
++
++class NamedPipe;
++
++class Terminal
++{
++public:
++    explicit Terminal(NamedPipe &output, bool plainMode, bool outputColor)
++        : m_output(output), m_plainMode(plainMode), m_outputColor(outputColor)
++    {
++    }
++
++    enum SendClearFlag { OmitClear, SendClear };
++    void reset(SendClearFlag sendClearFirst, int64_t newLine);
++    void sendLine(int64_t line, const CHAR_INFO *lineData, int width,
++                  int cursorColumn);
++    void showTerminalCursor(int column, int64_t line);
++    void hideTerminalCursor();
++
++private:
++    void moveTerminalToLine(int64_t line);
++
++public:
++    void enableMouseMode(bool enabled);
++
++private:
++    NamedPipe &m_output;
++    int64_t m_remoteLine = 0;
++    int m_remoteColumn = 0;
++    bool m_lineDataValid = true;
++    std::vector<CHAR_INFO> m_lineData;
++    bool m_cursorHidden = false;
++    int m_remoteColor = -1;
++    std::string m_termLineWorkingBuffer;
++    bool m_plainMode = false;
++    bool m_outputColor = true;
++    bool m_mouseModeEnabled = false;
++};
++
++#endif // TERMINAL_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6b0de3eff9f338c6571ff120ce32d7f606ee9dce
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,157 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef UNICODE_ENCODING_H
++#define UNICODE_ENCODING_H
++
++#include <stdint.h>
++
++// Encode the Unicode codepoint with UTF-8.  The buffer must be at least 4
++// bytes in size.
++static inline int encodeUtf8(char *out, uint32_t code) {
++    if (code < 0x80) {
++        out[0] = code;
++        return 1;
++    } else if (code < 0x800) {
++        out[0] = ((code >> 6) & 0x1F) | 0xC0;
++        out[1] = ((code >> 0) & 0x3F) | 0x80;
++        return 2;
++    } else if (code < 0x10000) {
++        if (code >= 0xD800 && code <= 0xDFFF) {
++            // The code points 0xD800 to 0xDFFF are reserved for UTF-16
++            // surrogate pairs and do not have an encoding in UTF-8.
++            return 0;
++        }
++        out[0] = ((code >> 12) & 0x0F) | 0xE0;
++        out[1] = ((code >>  6) & 0x3F) | 0x80;
++        out[2] = ((code >>  0) & 0x3F) | 0x80;
++        return 3;
++    } else if (code < 0x110000) {
++        out[0] = ((code >> 18) & 0x07) | 0xF0;
++        out[1] = ((code >> 12) & 0x3F) | 0x80;
++        out[2] = ((code >>  6) & 0x3F) | 0x80;
++        out[3] = ((code >>  0) & 0x3F) | 0x80;
++        return 4;
++    } else {
++        // Encoding error
++        return 0;
++    }
++}
++
++// Encode the Unicode codepoint with UTF-16.  The buffer must be large enough
++// to hold the output -- either 1 or 2 elements.
++static inline int encodeUtf16(wchar_t *out, uint32_t code) {
++    if (code < 0x10000) {
++        if (code >= 0xD800 && code <= 0xDFFF) {
++            // The code points 0xD800 to 0xDFFF are reserved for UTF-16
++            // surrogate pairs and do not have an encoding in UTF-16.
++            return 0;
++        }
++        out[0] = code;
++        return 1;
++    } else if (code < 0x110000) {
++        code -= 0x10000;
++        out[0] = 0xD800 | (code >> 10);
++        out[1] = 0xDC00 | (code & 0x3FF);
++        return 2;
++    } else {
++        // Encoding error
++        return 0;
++    }
++}
++
++// Return the byte size of a UTF-8 character using the value of the first
++// byte.
++static inline int utf8CharLength(char firstByte) {
++    // This code would probably be faster if it used __builtin_clz.
++    if ((firstByte & 0x80) == 0) {
++        return 1;
++    } else if ((firstByte & 0xE0) == 0xC0) {
++        return 2;
++    } else if ((firstByte & 0xF0) == 0xE0) {
++        return 3;
++    } else if ((firstByte & 0xF8) == 0xF0) {
++        return 4;
++    } else {
++        // Malformed UTF-8.
++        return 0;
++    }
++}
++
++// The pointer must point to 1-4 bytes, as indicated by the first byte.
++// Returns -1 on decoding error.
++static inline uint32_t decodeUtf8(const char *in) {
++    const uint32_t kInvalid = static_cast<uint32_t>(-1);
++    switch (utf8CharLength(in[0])) {
++        case 1: {
++            return in[0];
++        }
++        case 2: {
++            if ((in[1] & 0xC0) != 0x80) {
++                return kInvalid;
++            }
++            uint32_t tmp = 0;
++            tmp = (in[0] & 0x1F) << 6;
++            tmp |= (in[1] & 0x3F);
++            return tmp <= 0x7F ? kInvalid : tmp;
++        }
++        case 3: {
++            if ((in[1] & 0xC0) != 0x80 ||
++                    (in[2] & 0xC0) != 0x80) {
++                return kInvalid;
++            }
++            uint32_t tmp = 0;
++            tmp = (in[0] & 0x0F) << 12;
++            tmp |= (in[1] & 0x3F) << 6;
++            tmp |= (in[2] & 0x3F);
++            if (tmp <= 0x07FF || (tmp >= 0xD800 && tmp <= 0xDFFF)) {
++                return kInvalid;
++            } else {
++                return tmp;
++            }
++        }
++        case 4: {
++            if ((in[1] & 0xC0) != 0x80 ||
++                    (in[2] & 0xC0) != 0x80 ||
++                    (in[3] & 0xC0) != 0x80) {
++                return kInvalid;
++            }
++            uint32_t tmp = 0;
++            tmp = (in[0] & 0x07) << 18;
++            tmp |= (in[1] & 0x3F) << 12;
++            tmp |= (in[2] & 0x3F) << 6;
++            tmp |= (in[3] & 0x3F);
++            if (tmp <= 0xFFFF || tmp > 0x10FFFF) {
++                return kInvalid;
++            } else {
++                return tmp;
++            }
++        }
++        default: {
++            return kInvalid;
++        }
++    }
++}
++
++static inline uint32_t decodeSurrogatePair(wchar_t ch1, wchar_t ch2) {
++    return ((ch1 - 0xD800) << 10) + (ch2 - 0xDC00) + 0x10000;
++}
++
++#endif // UNICODE_ENCODING_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cd4abeb19168bcd6dc3c0d376bf0332b8ea02443
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,189 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++// Encode every code-point using this module and verify that it matches the
++// encoding generated using Windows WideCharToMultiByte.
++
++#include "UnicodeEncoding.h"
++
++#include <windows.h>
++#include <assert.h>
++#include <stdio.h>
++#include <string.h>
++#include <time.h>
++
++static void correctnessByCode()
++{
++    char mbstr1[4];
++    char mbstr2[4];
++    wchar_t wch[2];
++    for (unsigned int code = 0; code < 0x110000; ++code) {
++
++        // Surrogate pair reserved region.
++        const bool isReserved = (code >= 0xD800 && code <= 0xDFFF);
++
++        int mblen1 = encodeUtf8(mbstr1, code);
++        if (isReserved ? mblen1 != 0 : mblen1 <= 0) {
++            printf("Error: 0x%04X: mblen1=%d\n", code, mblen1);
++            continue;
++        }
++
++        int wlen = encodeUtf16(wch, code);
++        if (isReserved ? wlen != 0 : wlen <= 0) {
++            printf("Error: 0x%04X: wlen=%d\n", code, wlen);
++            continue;
++        }
++
++        if (isReserved) {
++            continue;
++        }
++
++        if (mblen1 != utf8CharLength(mbstr1[0])) {
++            printf("Error: 0x%04X: mblen1=%d, utf8CharLength(mbstr1[0])=%d\n",
++                code, mblen1, utf8CharLength(mbstr1[0]));
++            continue;
++        }
++
++        if (code != decodeUtf8(mbstr1)) {
++            printf("Error: 0x%04X: decodeUtf8(mbstr1)=%u\n",
++                code, decodeUtf8(mbstr1));
++            continue;
++        }
++
++        int mblen2 = WideCharToMultiByte(CP_UTF8, 0, wch, wlen, mbstr2, 4, NULL, NULL);
++        if (mblen1 != mblen2) {
++            printf("Error: 0x%04X: mblen1=%d, mblen2=%d\n", code, mblen1, mblen2);
++            continue;
++        }
++
++        if (memcmp(mbstr1, mbstr2, mblen1) != 0) {
++            printf("Error: 0x%04x: encodings are different\n", code);
++            continue;
++        }
++    }
++}
++
++static const char *encodingStr(char (&output)[128], char (&buf)[4])
++{
++    sprintf(output, "Encoding %02X %02X %02X %02X",
++        static_cast<uint8_t>(buf[0]),
++        static_cast<uint8_t>(buf[1]),
++        static_cast<uint8_t>(buf[2]),
++        static_cast<uint8_t>(buf[3]));
++    return output;
++}
++
++// This test can take a couple of minutes to run.
++static void correctnessByUtf8Encoding()
++{
++    for (uint64_t encoding = 0; encoding <= 0xFFFFFFFF; ++encoding) {
++
++        char mb[4];
++        mb[0] = encoding;
++        mb[1] = encoding >> 8;
++        mb[2] = encoding >> 16;
++        mb[3] = encoding >> 24;
++
++        const int mblen = utf8CharLength(mb[0]);
++        if (mblen == 0) {
++            continue;
++        }
++
++        // Test this module.
++        const uint32_t code1 = decodeUtf8(mb);
++        wchar_t ws1[2] = {};
++        const int wslen1 = encodeUtf16(ws1, code1);
++
++        // Test using Windows.  We can't decode a codepoint directly; we have
++        // to do UTF8->UTF16, then decode the surrogate pair.
++        wchar_t ws2[2] = {};
++        const int wslen2 = MultiByteToWideChar(
++            CP_UTF8, MB_ERR_INVALID_CHARS, mb, mblen, ws2, 2);
++        const uint32_t code2 =
++            (wslen2 == 1 ? ws2[0] :
++             wslen2 == 2 ? decodeSurrogatePair(ws2[0], ws2[1]) :
++             static_cast<uint32_t>(-1));
++
++        // Verify that the two implementations match.
++        char prefix[128];
++        if (code1 != code2) {
++            printf("%s: code1=0x%04x code2=0x%04x\n",
++                encodingStr(prefix, mb),
++                code1, code2);
++            continue;
++        }
++        if (wslen1 != wslen2) {
++            printf("%s: wslen1=%d wslen2=%d\n",
++                encodingStr(prefix, mb),
++                wslen1, wslen2);
++            continue;
++        }
++        if (memcmp(ws1, ws2, wslen1 * sizeof(wchar_t)) != 0) {
++            printf("%s: ws1 != ws2\n", encodingStr(prefix, mb));
++            continue;
++        }
++    }
++}
++
++wchar_t g_wch_TEST[] = { 0xD840, 0xDC00 };
++char g_ch_TEST[4];
++wchar_t *volatile g_pwch = g_wch_TEST;
++char *volatile g_pch = g_ch_TEST;
++unsigned int volatile g_code = 0xA2000;
++
++static void performance()
++{
++    {
++        clock_t start = clock();
++        for (long long i = 0; i < 250000000LL; ++i) {
++            int mblen = WideCharToMultiByte(CP_UTF8, 0, g_pwch, 2, g_pch, 4, NULL, NULL);
++            assert(mblen == 4);
++        }
++        clock_t stop = clock();
++        printf("%.3fns per char\n", (double)(stop - start) / CLOCKS_PER_SEC * 4.0);
++    }
++
++    {
++        clock_t start = clock();
++        for (long long i = 0; i < 3000000000LL; ++i) {
++            int mblen = encodeUtf8(g_pch, g_code);
++            assert(mblen == 4);
++        }
++        clock_t stop = clock();
++        printf("%.3fns per char\n", (double)(stop - start) / CLOCKS_PER_SEC / 3.0);
++    }
++}
++
++int main()
++{
++    printf("Testing correctnessByCode...\n");
++    fflush(stdout);
++    correctnessByCode();
++
++    printf("Testing correctnessByUtf8Encoding... (may take a couple minutes)\n");
++    fflush(stdout);
++    correctnessByUtf8Encoding();
++
++    printf("Testing performance...\n");
++    fflush(stdout);
++    performance();
++
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d53de021f5a2b70bea1b6d3395c53e2322997d69
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,107 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Win32Console.h"
++
++#include <windows.h>
++#include <wchar.h>
++
++#include <string>
++
++#include "../shared/DebugClient.h"
++#include "../shared/WinptyAssert.h"
++
++Win32Console::Win32Console() : m_titleWorkBuf(16)
++{
++    // The console window must be non-NULL.  It is used for two purposes:
++    //  (1) "Freezing" the console to detect the exact number of lines that
++    //      have scrolled.
++    //  (2) Killing processes attached to the console, by posting a WM_CLOSE
++    //      message to the console window.
++    m_hwnd = GetConsoleWindow();
++    ASSERT(m_hwnd != nullptr);
++}
++
++std::wstring Win32Console::title()
++{
++    while (true) {
++        // Calling GetConsoleTitleW is tricky, because its behavior changed
++        // from XP->Vista, then again from Win7->Win8.  The Vista+Win7 behavior
++        // is especially broken.
++        //
++        // The MSDN documentation documents nSize as the "size of the buffer
++        // pointed to by the lpConsoleTitle parameter, in characters" and the
++        // successful return value as "the length of the console window's
++        // title, in characters."
++        //
++        // On XP, the function returns the title length, AFTER truncation
++        // (excluding the NUL terminator).  If the title is blank, the API
++        // returns 0 and does not NUL-terminate the buffer.  To accommodate
++        // XP, the function must:
++        //  * Terminate the buffer itself.
++        //  * Double the size of the title buffer in a loop.
++        //
++        // On Vista and up, the function returns the non-truncated title
++        // length (excluding the NUL terminator).
++        //
++        // On Vista and Windows 7, there is a bug where the buffer size is
++        // interpreted as a byte count rather than a wchar_t count.  To
++        // work around this, we must pass GetConsoleTitleW a buffer that is
++        // twice as large as what is actually needed.
++        //
++        // See misc/*/Test_GetConsoleTitleW.cc for tests demonstrating Windows'
++        // behavior.
++
++        DWORD count = GetConsoleTitleW(m_titleWorkBuf.data(),
++                                       m_titleWorkBuf.size());
++        const size_t needed = (count + 1) * sizeof(wchar_t);
++        if (m_titleWorkBuf.size() < needed) {
++            m_titleWorkBuf.resize(needed);
++            continue;
++        }
++        m_titleWorkBuf[count] = L'\0';
++        return m_titleWorkBuf.data();
++    }
++}
++
++void Win32Console::setTitle(const std::wstring &title)
++{
++    if (!SetConsoleTitleW(title.c_str())) {
++        trace("SetConsoleTitleW failed");
++    }
++}
++
++void Win32Console::setFrozen(bool frozen) {
++    const int SC_CONSOLE_MARK = 0xFFF2;
++    const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
++    if (frozen == m_frozen) {
++        // Do nothing.
++    } else if (frozen) {
++        // Enter selection mode by activating either Mark or SelectAll.
++        const int command = m_freezeUsesMark ? SC_CONSOLE_MARK
++                                             : SC_CONSOLE_SELECT_ALL;
++        SendMessage(m_hwnd, WM_SYSCOMMAND, command, 0);
++        m_frozen = true;
++    } else {
++        // Send Escape to cancel the selection.
++        SendMessage(m_hwnd, WM_CHAR, 27, 0x00010001);
++        m_frozen = false;
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ed83877e99301be3e9288dc071da64a7a9371d2c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,67 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_WIN32_CONSOLE_H
++#define AGENT_WIN32_CONSOLE_H
++
++#include <windows.h>
++
++#include <string>
++#include <vector>
++
++class Win32Console
++{
++public:
++    class FreezeGuard {
++    public:
++        FreezeGuard(Win32Console &console, bool frozen) :
++                m_console(console), m_previous(console.frozen()) {
++            m_console.setFrozen(frozen);
++        }
++        ~FreezeGuard() {
++            m_console.setFrozen(m_previous);
++        }
++        FreezeGuard(const FreezeGuard &other) = delete;
++        FreezeGuard &operator=(const FreezeGuard &other) = delete;
++    private:
++        Win32Console &m_console;
++        bool m_previous;
++    };
++
++    Win32Console();
++
++    HWND hwnd() { return m_hwnd; }
++    std::wstring title();
++    void setTitle(const std::wstring &title);
++    void setFreezeUsesMark(bool useMark) { m_freezeUsesMark = useMark; }
++    void setNewW10(bool isNewW10) { m_isNewW10 = isNewW10; }
++    bool isNewW10() { return m_isNewW10; }
++    void setFrozen(bool frozen=true);
++    bool frozen() { return m_frozen; }
++
++private:
++    HWND m_hwnd = nullptr;
++    bool m_frozen = false;
++    bool m_freezeUsesMark = false;
++    bool m_isNewW10 = false;
++    std::vector<wchar_t> m_titleWorkBuf;
++};
++
++#endif // AGENT_WIN32_CONSOLE_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ed93f4081f87ad823a63dd0a23e3e03611615bf0
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,193 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Win32ConsoleBuffer.h"
++
++#include <windows.h>
++
++#include "../shared/DebugClient.h"
++#include "../shared/StringBuilder.h"
++#include "../shared/WinptyAssert.h"
++
++std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::openStdout() {
++    return std::unique_ptr<Win32ConsoleBuffer>(
++        new Win32ConsoleBuffer(GetStdHandle(STD_OUTPUT_HANDLE), false));
++}
++
++std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::openConout() {
++    const HANDLE conout = CreateFileW(L"CONOUT$",
++                                      GENERIC_READ | GENERIC_WRITE,
++                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
++                                      NULL, OPEN_EXISTING, 0, NULL);
++    ASSERT(conout != INVALID_HANDLE_VALUE);
++    return std::unique_ptr<Win32ConsoleBuffer>(
++        new Win32ConsoleBuffer(conout, true));
++}
++
++std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::createErrorBuffer() {
++    SECURITY_ATTRIBUTES sa = {};
++    sa.nLength = sizeof(sa);
++    sa.bInheritHandle = TRUE;
++    const HANDLE conout =
++        CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
++                                  FILE_SHARE_READ | FILE_SHARE_WRITE,
++                                  &sa,
++                                  CONSOLE_TEXTMODE_BUFFER,
++                                  nullptr);
++    ASSERT(conout != INVALID_HANDLE_VALUE);
++    return std::unique_ptr<Win32ConsoleBuffer>(
++        new Win32ConsoleBuffer(conout, true));
++}
++
++HANDLE Win32ConsoleBuffer::conout() {
++    return m_conout;
++}
++
++void Win32ConsoleBuffer::clearLines(
++        int row,
++        int count,
++        const ConsoleScreenBufferInfo &info) {
++    // TODO: error handling
++    const int width = info.bufferSize().X;
++    DWORD actual = 0;
++    if (!FillConsoleOutputCharacterW(
++            m_conout, L' ', width * count, Coord(0, row),
++            &actual) || static_cast<int>(actual) != width * count) {
++        trace("FillConsoleOutputCharacterW failed");
++    }
++    if (!FillConsoleOutputAttribute(
++            m_conout, kDefaultAttributes, width * count, Coord(0, row),
++            &actual) || static_cast<int>(actual) != width * count) {
++        trace("FillConsoleOutputAttribute failed");
++    }
++}
++
++void Win32ConsoleBuffer::clearAllLines(const ConsoleScreenBufferInfo &info) {
++    clearLines(0, info.bufferSize().Y, info);
++}
++
++ConsoleScreenBufferInfo Win32ConsoleBuffer::bufferInfo() {
++    // TODO: error handling
++    ConsoleScreenBufferInfo info;
++    if (!GetConsoleScreenBufferInfo(m_conout, &info)) {
++        trace("GetConsoleScreenBufferInfo failed");
++    }
++    return info;
++}
++
++Coord Win32ConsoleBuffer::bufferSize() {
++    return bufferInfo().bufferSize();
++}
++
++SmallRect Win32ConsoleBuffer::windowRect() {
++    return bufferInfo().windowRect();
++}
++
++bool Win32ConsoleBuffer::resizeBufferRange(const Coord &initialSize,
++                                           Coord &finalSize) {
++    if (SetConsoleScreenBufferSize(m_conout, initialSize)) {
++        finalSize = initialSize;
++        return true;
++    }
++    // The font might be too small to accommodate a very narrow console window.
++    // In that case, rather than simply give up, it's better to try wider
++    // buffer sizes until the call succeeds.
++    Coord size = initialSize;
++    while (size.X < 20) {
++        size.X++;
++        if (SetConsoleScreenBufferSize(m_conout, size)) {
++            finalSize = size;
++            trace("SetConsoleScreenBufferSize: initial size (%d,%d) failed, "
++                  "but wider size (%d,%d) succeeded",
++                  initialSize.X, initialSize.Y,
++                  finalSize.X, finalSize.Y);
++            return true;
++        }
++    }
++    trace("SetConsoleScreenBufferSize failed: "
++          "tried (%d,%d) through (%d,%d)",
++          initialSize.X, initialSize.Y,
++          size.X, size.Y);
++    return false;
++}
++
++void Win32ConsoleBuffer::resizeBuffer(const Coord &size) {
++    // TODO: error handling
++    if (!SetConsoleScreenBufferSize(m_conout, size)) {
++        trace("SetConsoleScreenBufferSize failed: size=(%d,%d)",
++              size.X, size.Y);
++    }
++}
++
++void Win32ConsoleBuffer::moveWindow(const SmallRect &rect) {
++    // TODO: error handling
++    if (!SetConsoleWindowInfo(m_conout, TRUE, &rect)) {
++        trace("SetConsoleWindowInfo failed");
++    }
++}
++
++Coord Win32ConsoleBuffer::cursorPosition() {
++    return bufferInfo().dwCursorPosition;
++}
++
++void Win32ConsoleBuffer::setCursorPosition(const Coord &coord) {
++    // TODO: error handling
++    if (!SetConsoleCursorPosition(m_conout, coord)) {
++        trace("SetConsoleCursorPosition failed");
++    }
++}
++
++void Win32ConsoleBuffer::read(const SmallRect &rect, CHAR_INFO *data) {
++    // TODO: error handling
++    SmallRect tmp(rect);
++    if (!ReadConsoleOutputW(m_conout, data, rect.size(), Coord(), &tmp) &&
++            isTracingEnabled()) {
++        StringBuilder sb(256);
++        auto outStruct = [&](const SMALL_RECT &sr) {
++            sb << "{L=" << sr.Left << ",T=" << sr.Top
++               << ",R=" << sr.Right << ",B=" << sr.Bottom << '}';
++        };
++        sb << "Win32ConsoleBuffer::read: ReadConsoleOutput failed: readRegion=";
++        outStruct(rect);
++        CONSOLE_SCREEN_BUFFER_INFO info = {};
++        if (GetConsoleScreenBufferInfo(m_conout, &info)) {
++            sb << ", dwSize=(" << info.dwSize.X << ',' << info.dwSize.Y
++               << "), srWindow=";
++            outStruct(info.srWindow);
++        } else {
++            sb << ", GetConsoleScreenBufferInfo also failed";
++        }
++        trace("%s", sb.c_str());
++    }
++}
++
++void Win32ConsoleBuffer::write(const SmallRect &rect, const CHAR_INFO *data) {
++    // TODO: error handling
++    SmallRect tmp(rect);
++    if (!WriteConsoleOutputW(m_conout, data, rect.size(), Coord(), &tmp)) {
++        trace("WriteConsoleOutput failed");
++    }
++}
++
++void Win32ConsoleBuffer::setTextAttribute(WORD attributes) {
++    if (!SetConsoleTextAttribute(m_conout, attributes)) {
++        trace("SetConsoleTextAttribute failed");
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a68d8d304fd32ad4afde660d1fe534c47e85d4a7
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,99 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef AGENT_WIN32_CONSOLE_BUFFER_H
++#define AGENT_WIN32_CONSOLE_BUFFER_H
++
++#include <windows.h>
++
++#include <string.h>
++
++#include <memory>
++
++#include "Coord.h"
++#include "SmallRect.h"
++
++class ConsoleScreenBufferInfo : public CONSOLE_SCREEN_BUFFER_INFO {
++public:
++    ConsoleScreenBufferInfo()
++    {
++        memset(this, 0, sizeof(*this));
++    }
++
++    Coord bufferSize() const        { return dwSize;    }
++    SmallRect windowRect() const    { return srWindow;  }
++    Coord cursorPosition() const    { return dwCursorPosition; }
++};
++
++class Win32ConsoleBuffer {
++private:
++    Win32ConsoleBuffer(HANDLE conout, bool owned) :
++        m_conout(conout), m_owned(owned)
++    {
++    }
++
++public:
++    static const int kDefaultAttributes = 7;
++
++    ~Win32ConsoleBuffer() {
++        if (m_owned) {
++            CloseHandle(m_conout);
++        }
++    }
++
++    static std::unique_ptr<Win32ConsoleBuffer> openStdout();
++    static std::unique_ptr<Win32ConsoleBuffer> openConout();
++    static std::unique_ptr<Win32ConsoleBuffer> createErrorBuffer();
++
++    Win32ConsoleBuffer(const Win32ConsoleBuffer &other) = delete;
++    Win32ConsoleBuffer &operator=(const Win32ConsoleBuffer &other) = delete;
++
++    HANDLE conout();
++    void clearLines(int row, int count, const ConsoleScreenBufferInfo &info);
++    void clearAllLines(const ConsoleScreenBufferInfo &info);
++
++    // Buffer and window sizes.
++    ConsoleScreenBufferInfo bufferInfo();
++    Coord bufferSize();
++    SmallRect windowRect();
++    void resizeBuffer(const Coord &size);
++    bool resizeBufferRange(const Coord &initialSize, Coord &finalSize);
++    bool resizeBufferRange(const Coord &initialSize) {
++        Coord dummy;
++        return resizeBufferRange(initialSize, dummy);
++    }
++    void moveWindow(const SmallRect &rect);
++
++    // Cursor.
++    Coord cursorPosition();
++    void setCursorPosition(const Coord &point);
++
++    // Screen content.
++    void read(const SmallRect &rect, CHAR_INFO *data);
++    void write(const SmallRect &rect, const CHAR_INFO *data);
++
++    void setTextAttribute(WORD attributes);
++
++private:
++    HANDLE m_conout = nullptr;
++    bool m_owned = false;
++};
++
++#endif // AGENT_WIN32_CONSOLE_BUFFER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2420fde4d8bca81dffd1728c7373d9521da33ae1
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,114 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <wchar.h>
++
++#include "../shared/StringUtil.h"
++#include "../shared/WindowsVersion.h"
++#include "../shared/WinptyAssert.h"
++#include "../shared/WinptyVersion.h"
++
++#include "Agent.h"
++#include "AgentCreateDesktop.h"
++#include "DebugShowInput.h"
++
++const char USAGE[] =
++"Usage: %ls controlPipeName flags mouseMode cols rows\n"
++"Usage: %ls controlPipeName --create-desktop\n"
++"\n"
++"Ordinarily, this program is launched by winpty.dll and is not directly\n"
++"useful to winpty users.  However, it also has options intended for\n"
++"debugging winpty.\n"
++"\n"
++"Usage: %ls [options]\n"
++"\n"
++"Options:\n"
++"  --show-input [--with-mouse] [--escape-input]\n"
++"                   Dump INPUT_RECORDs from the console input buffer\n"
++"                   --with-mouse: Include MOUSE_INPUT_RECORDs in the dump\n"
++"                       output\n"
++"                   --escape-input: Direct the new Windows 10 console to use\n"
++"                       escape sequences for input\n"
++"  --version        Print the winpty version\n";
++
++static uint64_t winpty_atoi64(const char *str) {
++    return strtoll(str, NULL, 10);
++}
++
++int main() {
++    dumpWindowsVersion();
++    dumpVersionToTrace();
++
++    // Technically, we should free the CommandLineToArgvW return value using
++    // a single call to LocalFree, but the call will never actually happen in
++    // the normal case.
++    int argc = 0;
++    wchar_t *cmdline = GetCommandLineW();
++    ASSERT(cmdline != nullptr && "GetCommandLineW returned NULL");
++    wchar_t **argv = CommandLineToArgvW(cmdline, &argc);
++    ASSERT(argv != nullptr && "CommandLineToArgvW returned NULL");
++
++    if (argc == 2 && !wcscmp(argv[1], L"--version")) {
++        dumpVersionToStdout();
++        return 0;
++    }
++
++    if (argc >= 2 && !wcscmp(argv[1], L"--show-input")) {
++        bool withMouse = false;
++        bool escapeInput = false;
++        for (int i = 2; i < argc; ++i) {
++            if (!wcscmp(argv[i], L"--with-mouse")) {
++                withMouse = true;
++            } else if (!wcscmp(argv[i], L"--escape-input")) {
++                escapeInput = true;
++            } else {
++                fprintf(stderr, "Unrecognized --show-input option: %ls\n",
++                    argv[i]);
++                return 1;
++            }
++        }
++        debugShowInput(withMouse, escapeInput);
++        return 0;
++    }
++
++    if (argc == 3 && !wcscmp(argv[2], L"--create-desktop")) {
++        handleCreateDesktop(argv[1]);
++        return 0;
++    }
++
++    if (argc != 6) {
++        fprintf(stderr, USAGE, argv[0], argv[0], argv[0]);
++        return 1;
++    }
++
++    Agent agent(argv[1],
++                winpty_atoi64(utf8FromWide(argv[2]).c_str()),
++                atoi(utf8FromWide(argv[3]).c_str()),
++                atoi(utf8FromWide(argv[4]).c_str()),
++                atoi(utf8FromWide(argv[5]).c_str()));
++    agent.run();
++
++    // The Agent destructor shouldn't return, but if it does, exit
++    // unsuccessfully.
++    return 1;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1c7d37e3e531f4ad6de14ee5bd49b34b43608cbe
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,61 @@@
++# Copyright (c) 2011-2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++ALL_TARGETS += build/winpty-agent.exe
++
++$(eval $(call def_mingw_target,agent,-DWINPTY_AGENT_ASSERT))
++
++AGENT_OBJECTS = \
++      build/agent/agent/Agent.o \
++      build/agent/agent/AgentCreateDesktop.o \
++      build/agent/agent/ConsoleFont.o \
++      build/agent/agent/ConsoleInput.o \
++      build/agent/agent/ConsoleInputReencoding.o \
++      build/agent/agent/ConsoleLine.o \
++      build/agent/agent/DebugShowInput.o \
++      build/agent/agent/DefaultInputMap.o \
++      build/agent/agent/EventLoop.o \
++      build/agent/agent/InputMap.o \
++      build/agent/agent/LargeConsoleRead.o \
++      build/agent/agent/NamedPipe.o \
++      build/agent/agent/Scraper.o \
++      build/agent/agent/Terminal.o \
++      build/agent/agent/Win32Console.o \
++      build/agent/agent/Win32ConsoleBuffer.o \
++      build/agent/agent/main.o \
++      build/agent/shared/BackgroundDesktop.o \
++      build/agent/shared/Buffer.o \
++      build/agent/shared/DebugClient.o \
++      build/agent/shared/GenRandom.o \
++      build/agent/shared/OwnedHandle.o \
++      build/agent/shared/StringUtil.o \
++      build/agent/shared/WindowsSecurity.o \
++      build/agent/shared/WindowsVersion.o \
++      build/agent/shared/WinptyAssert.o \
++      build/agent/shared/WinptyException.o \
++      build/agent/shared/WinptyVersion.o
++
++build/agent/shared/WinptyVersion.o : build/gen/GenVersion.h
++
++build/winpty-agent.exe : $(AGENT_OBJECTS)
++      $(info Linking $@)
++      @$(MINGW_CXX) $(MINGW_LDFLAGS) -o $@ $^
++
++-include $(AGENT_OBJECTS:.o=.d)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e990a60338e08eb771a183577de9d82d42584fae
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,60 @@@
++# By default gyp/msbuild build for 32-bit Windows.  This gyp include file
++# defines configurations for both 32-bit and 64-bit Windows.  To use it, run:
++#
++#     C:\...\winpty\src>gyp -I configurations.gypi
++#
++# This command generates Visual Studio project files with a Release
++# configuration and two Platforms--Win32 and x64.  Both can be built:
++#
++#     C:\...\winpty\src>msbuild winpty.sln /p:Platform=Win32
++#     C:\...\winpty\src>msbuild winpty.sln /p:Platform=x64
++#
++# The output is placed in:
++#
++#     C:\...\winpty\src\Release\Win32
++#     C:\...\winpty\src\Release\x64
++#
++# Windows XP note: By default, the project files will use the default "toolset"
++# for the given MSVC version.  For MSVC 2013 and MSVC 2015, the default toolset
++# generates binaries that do not run on Windows XP.  To target Windows XP,
++# select the XP-specific toolset by passing
++# -D WINPTY_MSBUILD_TOOLSET={v120_xp,v140_xp} to gyp (v120_xp == MSVC 2013,
++# v140_xp == MSVC 2015).  Unfortunately, it isn't possible to have a single
++# project file with configurations for both XP and post-XP.  This seems to be a
++# limitation of the MSVC project file format.
++#
++# This file is not included by default, because I suspect it would interfere
++# with node-gyp, which has a different system for building 32-vs-64-bit
++# binaries.  It uses a common.gypi, and the project files it generates can only
++# build a single architecture, the output paths are not differentiated by
++# architecture.
++
++{
++    'variables': {
++        'WINPTY_MSBUILD_TOOLSET%': '',
++    },
++    'target_defaults': {
++        'default_configuration': 'Release_Win32',
++        'configurations': {
++            'Release_Win32': {
++                'msvs_configuration_platform': 'Win32',
++            },
++            'Release_x64': {
++                'msvs_configuration_platform': 'x64',
++            },
++        },
++        'msvs_configuration_attributes': {
++            'OutputDirectory': '$(SolutionDir)$(ConfigurationName)\\$(Platform)',
++            'IntermediateDirectory': '$(ConfigurationName)\\$(Platform)\\obj\\$(ProjectName)',
++        },
++        'msvs_settings': {
++            'VCLinkerTool': {
++                'SubSystem': '1', # /SUBSYSTEM:CONSOLE
++            },
++            'VCCLCompilerTool': {
++                'RuntimeLibrary': '0', # MultiThreaded (/MT)
++            },
++        },
++        'msbuild_toolset' : '<(WINPTY_MSBUILD_TOOLSET)',
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..353d31c1c6e408feb803d47c993fdf3addd0a0d2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,117 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include <cstdio>
++#include <cstdlib>
++
++#include <windows.h>
++
++#include "../shared/WindowsSecurity.h"
++#include "../shared/WinptyException.h"
++
++const wchar_t *kPipeName = L"\\\\.\\pipe\\DebugServer";
++
++// A message may not be larger than this size.
++const int MSG_SIZE = 4096;
++
++static void usage(const char *program, int code) {
++    printf("Usage: %s [--everyone]\n"
++           "\n"
++           "Creates the named pipe %ls and reads messages.  Prints each\n"
++           "message to stdout.  By default, only the current user can send messages.\n"
++           "Pass --everyone to let anyone send a message.\n"
++           "\n"
++           "Use the WINPTY_DEBUG environment variable to enable winpty trace output.\n"
++           "(e.g. WINPTY_DEBUG=trace for the default trace output.)  Set WINPTYDBG=1\n"
++           "to enable trace with older winpty versions.\n",
++           program, kPipeName);
++    exit(code);
++}
++
++int main(int argc, char *argv[]) {
++    bool everyone = false;
++    for (int i = 1; i < argc; ++i) {
++        std::string arg = argv[i];
++        if (arg == "--everyone") {
++            everyone = true;
++        } else if (arg == "-h" || arg == "--help") {
++            usage(argv[0], 0);
++        } else {
++            usage(argv[0], 1);
++        }
++    }
++
++    SecurityDescriptor sd;
++    PSECURITY_ATTRIBUTES psa = nullptr;
++    SECURITY_ATTRIBUTES sa = {};
++    if (everyone) {
++        try {
++            sd = createPipeSecurityDescriptorOwnerFullControlEveryoneWrite();
++        } catch (const WinptyException &e) {
++            fprintf(stderr,
++                "error creating security descriptor: %ls\n", e.what());
++            exit(1);
++        }
++        sa.nLength = sizeof(sa);
++        sa.lpSecurityDescriptor = sd.get();
++        psa = &sa;
++    }
++
++    HANDLE serverPipe = CreateNamedPipeW(
++        kPipeName,
++        /*dwOpenMode=*/PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
++        /*dwPipeMode=*/PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE |
++            rejectRemoteClientsPipeFlag(),
++        /*nMaxInstances=*/1,
++        /*nOutBufferSize=*/MSG_SIZE,
++        /*nInBufferSize=*/MSG_SIZE,
++        /*nDefaultTimeOut=*/10 * 1000,
++        psa);
++
++    if (serverPipe == INVALID_HANDLE_VALUE) {
++        fprintf(stderr, "error: could not create %ls pipe: error %u\n",
++            kPipeName, static_cast<unsigned>(GetLastError()));
++        exit(1);
++    }
++
++    char msgBuffer[MSG_SIZE + 1];
++
++    while (true) {
++        if (!ConnectNamedPipe(serverPipe, nullptr)) {
++            fprintf(stderr, "error: ConnectNamedPipe failed\n");
++            fflush(stderr);
++            exit(1);
++        }
++        DWORD bytesRead = 0;
++        if (!ReadFile(serverPipe, msgBuffer, MSG_SIZE, &bytesRead, nullptr)) {
++            fprintf(stderr, "error: ReadFile on pipe failed\n");
++            fflush(stderr);
++            DisconnectNamedPipe(serverPipe);
++            continue;
++        }
++        msgBuffer[bytesRead] = '\n';
++        fwrite(msgBuffer, 1, bytesRead + 1, stdout);
++        fflush(stdout);
++
++        DWORD bytesWritten = 0;
++        WriteFile(serverPipe, "OK", 2, &bytesWritten, nullptr);
++        DisconnectNamedPipe(serverPipe);
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..beed1bd597d19f28eea54c3fbb083ed60f986911
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,41 @@@
++# Copyright (c) 2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++ALL_TARGETS += build/winpty-debugserver.exe
++
++$(eval $(call def_mingw_target,debugserver,))
++
++DEBUGSERVER_OBJECTS = \
++      build/debugserver/debugserver/DebugServer.o \
++      build/debugserver/shared/DebugClient.o \
++      build/debugserver/shared/OwnedHandle.o \
++      build/debugserver/shared/StringUtil.o \
++      build/debugserver/shared/WindowsSecurity.o \
++      build/debugserver/shared/WindowsVersion.o \
++      build/debugserver/shared/WinptyAssert.o \
++      build/debugserver/shared/WinptyException.o
++
++build/debugserver/shared/WindowsVersion.o : build/gen/GenVersion.h
++
++build/winpty-debugserver.exe : $(DEBUGSERVER_OBJECTS)
++      $(info Linking $@)
++      @$(MINGW_CXX) $(MINGW_LDFLAGS) -o $@ $^
++
++-include $(DEBUGSERVER_OBJECTS:.o=.d)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..fdfe4bca21d95aba995067eb521753bdbabfd40d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,242 @@@
++/*
++ * Copyright (c) 2011-2016 Ryan Prichard
++ *
++ * Permission is hereby granted, free of charge, to any person obtaining a copy
++ * of this software and associated documentation files (the "Software"), to
++ * deal in the Software without restriction, including without limitation the
++ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++ * sell copies of the Software, and to permit persons to whom the Software is
++ * furnished to do so, subject to the following conditions:
++ *
++ * The above copyright notice and this permission notice shall be included in
++ * all copies or substantial portions of the Software.
++ *
++ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++ * IN THE SOFTWARE.
++ */
++
++#ifndef WINPTY_H
++#define WINPTY_H
++
++#include <windows.h>
++
++#include "winpty_constants.h"
++
++/* On 32-bit Windows, winpty functions have the default __cdecl (not __stdcall)
++ * calling convention.  (64-bit Windows has only a single calling convention.)
++ * When compiled with __declspec(dllexport), with either MinGW or MSVC, the
++ * winpty functions are unadorned--no underscore prefix or '@nn' suffix--so
++ * GetProcAddress can be used easily. */
++#ifdef COMPILING_WINPTY_DLL
++#define WINPTY_API __declspec(dllexport)
++#else
++#define WINPTY_API __declspec(dllimport)
++#endif
++
++#ifdef __cplusplus
++extern "C" {
++#endif
++
++/* The winpty API uses wide characters, instead of UTF-8, to avoid conversion
++ * complications related to surrogates.  Windows generally tolerates unpaired
++ * surrogates in text, which makes conversion to and from UTF-8 ambiguous and
++ * complicated.  (There are different UTF-8 variants that deal with UTF-16
++ * surrogates differently.) */
++
++
++
++/*****************************************************************************
++ * Error handling. */
++
++/* All the APIs have an optional winpty_error_t output parameter.  If a
++ * non-NULL argument is specified, then either the API writes NULL to the
++ * value (on success) or writes a newly allocated winpty_error_t object.  The
++ * object must be freed using winpty_error_free. */
++
++/* An error object. */
++typedef struct winpty_error_s winpty_error_t;
++typedef winpty_error_t *winpty_error_ptr_t;
++
++/* An error code -- one of WINPTY_ERROR_xxx. */
++typedef DWORD winpty_result_t;
++
++/* Gets the error code from the error object. */
++WINPTY_API winpty_result_t winpty_error_code(winpty_error_ptr_t err);
++
++/* Returns a textual representation of the error.  The string is freed when
++ * the error is freed. */
++WINPTY_API LPCWSTR winpty_error_msg(winpty_error_ptr_t err);
++
++/* Free the error object.  Every error returned from the winpty API must be
++ * freed. */
++WINPTY_API void winpty_error_free(winpty_error_ptr_t err);
++
++
++
++/*****************************************************************************
++ * Configuration of a new agent. */
++
++/* The winpty_config_t object is not thread-safe. */
++typedef struct winpty_config_s winpty_config_t;
++
++/* Allocate a winpty_config_t value.  Returns NULL on error.  There are no
++ * required settings -- the object may immediately be used.  agentFlags is a
++ * set of zero or more WINPTY_FLAG_xxx values.  An unrecognized flag results
++ * in an assertion failure. */
++WINPTY_API winpty_config_t *
++winpty_config_new(UINT64 agentFlags, winpty_error_ptr_t *err /*OPTIONAL*/);
++
++/* Free the cfg object after passing it to winpty_open. */
++WINPTY_API void winpty_config_free(winpty_config_t *cfg);
++
++WINPTY_API void
++winpty_config_set_initial_size(winpty_config_t *cfg, int cols, int rows);
++
++/* Set the mouse mode to one of the WINPTY_MOUSE_MODE_xxx constants. */
++WINPTY_API void
++winpty_config_set_mouse_mode(winpty_config_t *cfg, int mouseMode);
++
++/* Amount of time to wait for the agent to startup and to wait for any given
++ * agent RPC request.  Must be greater than 0.  Can be INFINITE. */
++WINPTY_API void
++winpty_config_set_agent_timeout(winpty_config_t *cfg, DWORD timeoutMs);
++
++
++
++/*****************************************************************************
++ * Start the agent. */
++
++/* The winpty_t object is thread-safe. */
++typedef struct winpty_s winpty_t;
++
++/* Starts the agent.  Returns NULL on error.  This process will connect to the
++ * agent over a control pipe, and the agent will open data pipes (e.g. CONIN
++ * and CONOUT). */
++WINPTY_API winpty_t *
++winpty_open(const winpty_config_t *cfg,
++            winpty_error_ptr_t *err /*OPTIONAL*/);
++
++/* A handle to the agent process.  This value is valid for the lifetime of the
++ * winpty_t object.  Do not close it. */
++WINPTY_API HANDLE winpty_agent_process(winpty_t *wp);
++
++
++
++/*****************************************************************************
++ * I/O pipes. */
++
++/* Returns the names of named pipes used for terminal I/O.  Each input or
++ * output direction uses a different half-duplex pipe.  The agent creates
++ * these pipes, and the client can connect to them using ordinary I/O methods.
++ * The strings are freed when the winpty_t object is freed.
++ *
++ * winpty_conerr_name returns NULL unless WINPTY_FLAG_CONERR is specified.
++ *
++ * N.B.: CreateFile does not block when connecting to a local server pipe.  If
++ * the server pipe does not exist or is already connected, then it fails
++ * instantly. */
++WINPTY_API LPCWSTR winpty_conin_name(winpty_t *wp);
++WINPTY_API LPCWSTR winpty_conout_name(winpty_t *wp);
++WINPTY_API LPCWSTR winpty_conerr_name(winpty_t *wp);
++
++
++
++/*****************************************************************************
++ * winpty agent RPC call: process creation. */
++
++/* The winpty_spawn_config_t object is not thread-safe. */
++typedef struct winpty_spawn_config_s winpty_spawn_config_t;
++
++/* winpty_spawn_config strings do not need to live as long as the config
++ * object.  They are copied.  Returns NULL on error.  spawnFlags is a set of
++ * zero or more WINPTY_SPAWN_FLAG_xxx values.  An unrecognized flag results in
++ * an assertion failure.
++ *
++ * env is a a pointer to an environment block like that passed to
++ * CreateProcess--a contiguous array of NUL-terminated "VAR=VAL" strings
++ * followed by a final NUL terminator.
++ *
++ * N.B.: If you want to gather all of the child's output, you may want the
++ * WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN flag.
++ */
++WINPTY_API winpty_spawn_config_t *
++winpty_spawn_config_new(UINT64 spawnFlags,
++                        LPCWSTR appname /*OPTIONAL*/,
++                        LPCWSTR cmdline /*OPTIONAL*/,
++                        LPCWSTR cwd /*OPTIONAL*/,
++                        LPCWSTR env /*OPTIONAL*/,
++                        winpty_error_ptr_t *err /*OPTIONAL*/);
++
++/* Free the cfg object after passing it to winpty_spawn. */
++WINPTY_API void winpty_spawn_config_free(winpty_spawn_config_t *cfg);
++
++/*
++ * Spawns the new process.
++ *
++ * The function initializes all output parameters to zero or NULL.
++ *
++ * On success, the function returns TRUE.  For each of process_handle and
++ * thread_handle that is non-NULL, the HANDLE returned from CreateProcess is
++ * duplicated from the agent and returned to the winpty client.  The client is
++ * responsible for closing these HANDLES.
++ *
++ * On failure, the function returns FALSE, and if err is non-NULL, then *err
++ * is set to an error object.
++ *
++ * If the agent's CreateProcess call failed, then *create_process_error is set
++ * to GetLastError(), and the WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED error
++ * is returned.
++ *
++ * winpty_spawn can only be called once per winpty_t object.  If it is called
++ * before the output data pipe(s) is/are connected, then collected output is
++ * buffered until the pipes are connected, rather than being discarded.
++ *
++ * N.B.: GetProcessId works even if the process has exited.  The PID is not
++ * recycled until the NT process object is freed.
++ * (https://blogs.msdn.microsoft.com/oldnewthing/20110107-00/?p=11803)
++ */
++WINPTY_API BOOL
++winpty_spawn(winpty_t *wp,
++             const winpty_spawn_config_t *cfg,
++             HANDLE *process_handle /*OPTIONAL*/,
++             HANDLE *thread_handle /*OPTIONAL*/,
++             DWORD *create_process_error /*OPTIONAL*/,
++             winpty_error_ptr_t *err /*OPTIONAL*/);
++
++
++
++/*****************************************************************************
++ * winpty agent RPC calls: everything else */
++
++/* Change the size of the Windows console window. */
++WINPTY_API BOOL
++winpty_set_size(winpty_t *wp, int cols, int rows,
++                winpty_error_ptr_t *err /*OPTIONAL*/);
++
++/* Gets a list of processes attached to the console. */
++WINPTY_API int
++winpty_get_console_process_list(winpty_t *wp, int *processList, const int processCount,
++                                winpty_error_ptr_t *err /*OPTIONAL*/);
++
++/* Frees the winpty_t object and the OS resources contained in it.  This
++ * call breaks the connection with the agent, which should then close its
++ * console, terminating the processes attached to it.
++ *
++ * This function must not be called if any other threads are using the
++ * winpty_t object.  Undefined behavior results. */
++WINPTY_API void winpty_free(winpty_t *wp);
++
++
++
++/****************************************************************************/
++
++#ifdef __cplusplus
++}
++#endif
++
++#endif /* WINPTY_H */
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..11e34cf171c9c40def5437bfebd732af7c5438fd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,131 @@@
++/*
++ * Copyright (c) 2016 Ryan Prichard
++ *
++ * Permission is hereby granted, free of charge, to any person obtaining a copy
++ * of this software and associated documentation files (the "Software"), to
++ * deal in the Software without restriction, including without limitation the
++ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++ * sell copies of the Software, and to permit persons to whom the Software is
++ * furnished to do so, subject to the following conditions:
++ *
++ * The above copyright notice and this permission notice shall be included in
++ * all copies or substantial portions of the Software.
++ *
++ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++ * IN THE SOFTWARE.
++ */
++
++#ifndef WINPTY_CONSTANTS_H
++#define WINPTY_CONSTANTS_H
++
++/*
++ * You may want to include winpty.h instead, which includes this header.
++ *
++ * This file is split out from winpty.h so that the agent can access the
++ * winpty flags without also declaring the libwinpty APIs.
++ */
++
++/*****************************************************************************
++ * Error codes. */
++
++#define WINPTY_ERROR_SUCCESS                        0
++#define WINPTY_ERROR_OUT_OF_MEMORY                  1
++#define WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED    2
++#define WINPTY_ERROR_LOST_CONNECTION                3
++#define WINPTY_ERROR_AGENT_EXE_MISSING              4
++#define WINPTY_ERROR_UNSPECIFIED                    5
++#define WINPTY_ERROR_AGENT_DIED                     6
++#define WINPTY_ERROR_AGENT_TIMEOUT                  7
++#define WINPTY_ERROR_AGENT_CREATION_FAILED          8
++
++
++
++/*****************************************************************************
++ * Configuration of a new agent. */
++
++/* Create a new screen buffer (connected to the "conerr" terminal pipe) and
++ * pass it to child processes as the STDERR handle.  This flag also prevents
++ * the agent from reopening CONOUT$ when it polls -- regardless of whether the
++ * active screen buffer changes, winpty continues to monitor the original
++ * primary screen buffer. */
++#define WINPTY_FLAG_CONERR              0x1ull
++
++/* Don't output escape sequences. */
++#define WINPTY_FLAG_PLAIN_OUTPUT        0x2ull
++
++/* Do output color escape sequences.  These escapes are output by default, but
++ * are suppressed with WINPTY_FLAG_PLAIN_OUTPUT.  Use this flag to reenable
++ * them. */
++#define WINPTY_FLAG_COLOR_ESCAPES       0x4ull
++
++/* On XP and Vista, winpty needs to put the hidden console on a desktop in a
++ * service window station so that its polling does not interfere with other
++ * (visible) console windows.  To create this desktop, it must change the
++ * process' window station (i.e. SetProcessWindowStation) for the duration of
++ * the winpty_open call.  In theory, this change could interfere with the
++ * winpty client (e.g. other threads, spawning children), so winpty by default
++ * spawns a special agent process to create the hidden desktop.  Spawning
++ * processes on Windows is slow, though, so if
++ * WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION is set, winpty changes this
++ * process' window station instead.
++ * See https://github.com/rprichard/winpty/issues/58. */
++#define WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION 0x8ull
++
++#define WINPTY_FLAG_MASK (0ull \
++    | WINPTY_FLAG_CONERR \
++    | WINPTY_FLAG_PLAIN_OUTPUT \
++    | WINPTY_FLAG_COLOR_ESCAPES \
++    | WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION \
++)
++
++/* QuickEdit mode is initially disabled, and the agent does not send mouse
++ * mode sequences to the terminal.  If it receives mouse input, though, it
++ * still writes MOUSE_EVENT_RECORD values into CONIN. */
++#define WINPTY_MOUSE_MODE_NONE          0
++
++/* QuickEdit mode is initially enabled.  As CONIN enters or leaves mouse
++ * input mode (i.e. where ENABLE_MOUSE_INPUT is on and ENABLE_QUICK_EDIT_MODE
++ * is off), the agent enables or disables mouse input on the terminal.
++ *
++ * This is the default mode. */
++#define WINPTY_MOUSE_MODE_AUTO          1
++
++/* QuickEdit mode is initially disabled, and the agent enables the terminal's
++ * mouse input mode.  It does not disable terminal mouse mode (until exit). */
++#define WINPTY_MOUSE_MODE_FORCE         2
++
++
++
++/*****************************************************************************
++ * winpty agent RPC call: process creation. */
++
++/* If the spawn is marked "auto-shutdown", then the agent shuts down console
++ * output once the process exits.  The agent stops polling for new console
++ * output, and once all pending data has been written to the output pipe, the
++ * agent closes the pipe.  (At that point, the pipe may still have data in it,
++ * which the client may read.  Once all the data has been read, further reads
++ * return EOF.) */
++#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ull
++
++/* After the agent shuts down output, and after all output has been written
++ * into the pipe(s), exit the agent by closing the console.  If there any
++ * surviving processes still attached to the console, they are killed.
++ *
++ * Note: With this flag, an RPC call (e.g. winpty_set_size) issued after the
++ * agent exits will fail with an I/O or dead-agent error. */
++#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
++
++/* All the spawn flags. */
++#define WINPTY_SPAWN_FLAG_MASK (0ull \
++    | WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN \
++    | WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN \
++)
++
++
++
++#endif /* WINPTY_CONSTANTS_H */
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..82d00b2da2d2d26d168223011373d71a665809ab
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,75 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "AgentLocation.h"
++
++#include <windows.h>
++
++#include <string>
++
++#include "../shared/WinptyAssert.h"
++
++#include "LibWinptyException.h"
++
++#define AGENT_EXE L"winpty-agent.exe"
++
++static HMODULE getCurrentModule() {
++    HMODULE module;
++    if (!GetModuleHandleExW(
++                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
++                GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
++                reinterpret_cast<LPCWSTR>(getCurrentModule),
++                &module)) {
++        ASSERT(false && "GetModuleHandleEx failed");
++    }
++    return module;
++}
++
++static std::wstring getModuleFileName(HMODULE module) {
++    const int bufsize = 4096;
++    wchar_t path[bufsize];
++    int size = GetModuleFileNameW(module, path, bufsize);
++    ASSERT(size != 0 && size != bufsize);
++    return std::wstring(path);
++}
++
++static std::wstring dirname(const std::wstring &path) {
++    std::wstring::size_type pos = path.find_last_of(L"\\/");
++    if (pos == std::wstring::npos) {
++        return L"";
++    } else {
++        return path.substr(0, pos);
++    }
++}
++
++static bool pathExists(const std::wstring &path) {
++    return GetFileAttributesW(path.c_str()) != 0xFFFFFFFF;
++}
++
++std::wstring findAgentProgram() {
++    std::wstring progDir = dirname(getModuleFileName(getCurrentModule()));
++    std::wstring ret = progDir + (L"\\" AGENT_EXE);
++    if (!pathExists(ret)) {
++        throw LibWinptyException(
++            WINPTY_ERROR_AGENT_EXE_MISSING,
++            (L"agent executable does not exist: '" + ret + L"'").c_str());
++    }
++    return ret;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a96b854cd2a643e53b5e9b1c8ef1490f217c9d46
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,28 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef LIBWINPTY_AGENT_LOCATION_H
++#define LIBWINPTY_AGENT_LOCATION_H
++
++#include <string>
++
++std::wstring findAgentProgram();
++
++#endif // LIBWINPTY_AGENT_LOCATION_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2274798d238ed913115eae7d45c44c80977e8a57
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,54 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef LIB_WINPTY_EXCEPTION_H
++#define LIB_WINPTY_EXCEPTION_H
++
++#include "../include/winpty.h"
++
++#include "../shared/WinptyException.h"
++
++#include <memory>
++#include <string>
++
++class LibWinptyException : public WinptyException {
++public:
++    LibWinptyException(winpty_result_t code, const wchar_t *what) :
++        m_code(code), m_what(std::make_shared<std::wstring>(what)) {}
++
++    winpty_result_t code() const WINPTY_NOEXCEPT {
++        return m_code;
++    }
++
++    const wchar_t *what() const WINPTY_NOEXCEPT override {
++        return m_what->c_str();
++    }
++
++    std::shared_ptr<std::wstring> whatSharedStr() const WINPTY_NOEXCEPT {
++        return m_what;
++    }
++
++private:
++    winpty_result_t m_code;
++    // Using a shared_ptr ensures that copying the object raises no exception.
++    std::shared_ptr<std::wstring> m_what;
++};
++
++#endif // LIB_WINPTY_EXCEPTION_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..93e992d5c55961f30ca45972fa6026d31e9440a4
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,72 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef LIBWINPTY_WINPTY_INTERNAL_H
++#define LIBWINPTY_WINPTY_INTERNAL_H
++
++#include <memory>
++#include <string>
++
++#include "../include/winpty.h"
++
++#include "../shared/Mutex.h"
++#include "../shared/OwnedHandle.h"
++
++// The structures in this header are not intended to be accessed directly by
++// client programs.
++
++struct winpty_error_s {
++    winpty_result_t code;
++    const wchar_t *msgStatic;
++    // Use a pointer to a std::shared_ptr so that the struct remains simple
++    // enough to statically initialize, for the benefit of static error
++    // objects like kOutOfMemory.
++    std::shared_ptr<std::wstring> *msgDynamic;
++};
++
++struct winpty_config_s {
++    uint64_t flags = 0;
++    int cols = 80;
++    int rows = 25;
++    int mouseMode = WINPTY_MOUSE_MODE_AUTO;
++    DWORD timeoutMs = 30000;
++};
++
++struct winpty_s {
++    Mutex mutex;
++    OwnedHandle agentProcess;
++    OwnedHandle controlPipe;
++    DWORD agentTimeoutMs = 0;
++    OwnedHandle ioEvent;
++    std::wstring spawnDesktopName;
++    std::wstring coninPipeName;
++    std::wstring conoutPipeName;
++    std::wstring conerrPipeName;
++};
++
++struct winpty_spawn_config_s {
++    uint64_t winptyFlags = 0;
++    std::wstring appname;
++    std::wstring cmdline;
++    std::wstring cwd;
++    std::wstring env;
++};
++
++#endif // LIBWINPTY_WINPTY_INTERNAL_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ba32bad6e64a1dd342a7431183e13ed46ec5bbd6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,46 @@@
++# Copyright (c) 2011-2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++ALL_TARGETS += build/winpty.dll
++
++$(eval $(call def_mingw_target,libwinpty,-DCOMPILING_WINPTY_DLL))
++
++LIBWINPTY_OBJECTS = \
++      build/libwinpty/libwinpty/AgentLocation.o \
++      build/libwinpty/libwinpty/winpty.o \
++      build/libwinpty/shared/BackgroundDesktop.o \
++      build/libwinpty/shared/Buffer.o \
++      build/libwinpty/shared/DebugClient.o \
++      build/libwinpty/shared/GenRandom.o \
++      build/libwinpty/shared/OwnedHandle.o \
++      build/libwinpty/shared/StringUtil.o \
++      build/libwinpty/shared/WindowsSecurity.o \
++      build/libwinpty/shared/WindowsVersion.o \
++      build/libwinpty/shared/WinptyAssert.o \
++      build/libwinpty/shared/WinptyException.o \
++      build/libwinpty/shared/WinptyVersion.o
++
++build/libwinpty/shared/WinptyVersion.o : build/gen/GenVersion.h
++
++build/winpty.dll : $(LIBWINPTY_OBJECTS)
++      $(info Linking $@)
++      @$(MINGW_CXX) $(MINGW_LDFLAGS) -shared -o $@ $^ -Wl,--out-implib,build/winpty.lib
++
++-include $(LIBWINPTY_OBJECTS:.o=.d)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3d977498ef974c3ebf213f8a799fa29c57eb578f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,970 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include <windows.h>
++
++#include <stdint.h>
++#include <stdio.h>
++#include <string.h>
++
++#include <limits>
++#include <string>
++#include <vector>
++
++#include "../include/winpty.h"
++
++#include "../shared/AgentMsg.h"
++#include "../shared/BackgroundDesktop.h"
++#include "../shared/Buffer.h"
++#include "../shared/DebugClient.h"
++#include "../shared/GenRandom.h"
++#include "../shared/OwnedHandle.h"
++#include "../shared/StringBuilder.h"
++#include "../shared/StringUtil.h"
++#include "../shared/WindowsSecurity.h"
++#include "../shared/WindowsVersion.h"
++#include "../shared/WinptyAssert.h"
++#include "../shared/WinptyException.h"
++#include "../shared/WinptyVersion.h"
++
++#include "AgentLocation.h"
++#include "LibWinptyException.h"
++#include "WinptyInternal.h"
++
++
++
++/*****************************************************************************
++ * Error handling -- translate C++ exceptions to an optional error object
++ * output and log the result. */
++
++static const winpty_error_s kOutOfMemory = {
++    WINPTY_ERROR_OUT_OF_MEMORY,
++    L"Out of memory",
++    nullptr
++};
++
++static const winpty_error_s kBadRpcPacket = {
++    WINPTY_ERROR_UNSPECIFIED,
++    L"Bad RPC packet",
++    nullptr
++};
++
++static const winpty_error_s kUncaughtException = {
++    WINPTY_ERROR_UNSPECIFIED,
++    L"Uncaught C++ exception",
++    nullptr
++};
++
++/* Gets the error code from the error object. */
++WINPTY_API winpty_result_t winpty_error_code(winpty_error_ptr_t err) {
++    return err != nullptr ? err->code : WINPTY_ERROR_SUCCESS;
++}
++
++/* Returns a textual representation of the error.  The string is freed when
++ * the error is freed. */
++WINPTY_API LPCWSTR winpty_error_msg(winpty_error_ptr_t err) {
++    if (err != nullptr) {
++        if (err->msgStatic != nullptr) {
++            return err->msgStatic;
++        } else {
++            ASSERT(err->msgDynamic != nullptr);
++            std::wstring *msgPtr = err->msgDynamic->get();
++            ASSERT(msgPtr != nullptr);
++            return msgPtr->c_str();
++        }
++    } else {
++        return L"Success";
++    }
++}
++
++/* Free the error object.  Every error returned from the winpty API must be
++ * freed. */
++WINPTY_API void winpty_error_free(winpty_error_ptr_t err) {
++    if (err != nullptr && err->msgDynamic != nullptr) {
++        delete err->msgDynamic;
++        delete err;
++    }
++}
++
++static void translateException(winpty_error_ptr_t *&err) {
++    winpty_error_ptr_t ret = nullptr;
++    try {
++        try {
++            throw;
++        } catch (const ReadBuffer::DecodeError&) {
++            ret = const_cast<winpty_error_ptr_t>(&kBadRpcPacket);
++        } catch (const LibWinptyException &e) {
++            std::unique_ptr<winpty_error_t> obj(new winpty_error_t);
++            obj->code = e.code();
++            obj->msgStatic = nullptr;
++            obj->msgDynamic =
++                new std::shared_ptr<std::wstring>(e.whatSharedStr());
++            ret = obj.release();
++        } catch (const WinptyException &e) {
++            std::unique_ptr<winpty_error_t> obj(new winpty_error_t);
++            std::shared_ptr<std::wstring> msg(new std::wstring(e.what()));
++            obj->code = WINPTY_ERROR_UNSPECIFIED;
++            obj->msgStatic = nullptr;
++            obj->msgDynamic = new std::shared_ptr<std::wstring>(msg);
++            ret = obj.release();
++        }
++    } catch (const std::bad_alloc&) {
++        ret = const_cast<winpty_error_ptr_t>(&kOutOfMemory);
++    } catch (...) {
++        ret = const_cast<winpty_error_ptr_t>(&kUncaughtException);
++    }
++    trace("libwinpty error: code=%u msg='%s'",
++        static_cast<unsigned>(ret->code),
++        utf8FromWide(winpty_error_msg(ret)).c_str());
++    if (err != nullptr) {
++        *err = ret;
++    } else {
++        winpty_error_free(ret);
++    }
++}
++
++#define API_TRY \
++    if (err != nullptr) { *err = nullptr; } \
++    try
++
++#define API_CATCH(ret) \
++    catch (...) { translateException(err); return (ret); }
++
++
++
++/*****************************************************************************
++ * Configuration of a new agent. */
++
++WINPTY_API winpty_config_t *
++winpty_config_new(UINT64 flags, winpty_error_ptr_t *err /*OPTIONAL*/) {
++    API_TRY {
++        ASSERT((flags & WINPTY_FLAG_MASK) == flags);
++        std::unique_ptr<winpty_config_t> ret(new winpty_config_t);
++        ret->flags = flags;
++        return ret.release();
++    } API_CATCH(nullptr)
++}
++
++WINPTY_API void winpty_config_free(winpty_config_t *cfg) {
++    delete cfg;
++}
++
++WINPTY_API void
++winpty_config_set_initial_size(winpty_config_t *cfg, int cols, int rows) {
++    ASSERT(cfg != nullptr && cols > 0 && rows > 0);
++    cfg->cols = cols;
++    cfg->rows = rows;
++}
++
++WINPTY_API void
++winpty_config_set_mouse_mode(winpty_config_t *cfg, int mouseMode) {
++    ASSERT(cfg != nullptr &&
++        mouseMode >= WINPTY_MOUSE_MODE_NONE &&
++        mouseMode <= WINPTY_MOUSE_MODE_FORCE);
++    cfg->mouseMode = mouseMode;
++}
++
++WINPTY_API void
++winpty_config_set_agent_timeout(winpty_config_t *cfg, DWORD timeoutMs) {
++    ASSERT(cfg != nullptr && timeoutMs > 0);
++    cfg->timeoutMs = timeoutMs;
++}
++
++
++
++/*****************************************************************************
++ * Agent I/O. */
++
++namespace {
++
++// Once an I/O operation fails with ERROR_IO_PENDING, the caller *must* wait
++// for it to complete, even after calling CancelIo on it!  See
++// https://blogs.msdn.microsoft.com/oldnewthing/20110202-00/?p=11613.  This
++// class enforces that requirement.
++class PendingIo {
++    HANDLE m_file;
++    OVERLAPPED &m_over;
++    bool m_finished;
++public:
++    // The file handle and OVERLAPPED object must live as long as the PendingIo
++    // object.
++    PendingIo(HANDLE file, OVERLAPPED &over) :
++        m_file(file), m_over(over), m_finished(false) {}
++    ~PendingIo() {
++        if (!m_finished) {
++            // We're not usually that interested in CancelIo's return value.
++            // In any case, we must not throw an exception in this dtor.
++            CancelIo(m_file);
++            waitForCompletion();
++        }
++    }
++    std::tuple<BOOL, DWORD> waitForCompletion(DWORD &actual) WINPTY_NOEXCEPT {
++        m_finished = true;
++        const BOOL success =
++            GetOverlappedResult(m_file, &m_over, &actual, TRUE);
++        return std::make_tuple(success, GetLastError());
++    }
++    std::tuple<BOOL, DWORD> waitForCompletion() WINPTY_NOEXCEPT {
++        DWORD actual = 0;
++        return waitForCompletion(actual);
++    }
++};
++
++} // anonymous namespace
++
++static void handlePendingIo(winpty_t &wp, OVERLAPPED &over, BOOL &success,
++                            DWORD &lastError, DWORD &actual) {
++    if (!success && lastError == ERROR_IO_PENDING) {
++        PendingIo io(wp.controlPipe.get(), over);
++        const HANDLE waitHandles[2] = { wp.ioEvent.get(),
++                                        wp.agentProcess.get() };
++        DWORD waitRet = WaitForMultipleObjects(
++            2, waitHandles, FALSE, wp.agentTimeoutMs);
++        if (waitRet != WAIT_OBJECT_0) {
++            // The I/O is still pending.  Cancel it, close the I/O event, and
++            // throw an exception.
++            if (waitRet == WAIT_OBJECT_0 + 1) {
++                throw LibWinptyException(WINPTY_ERROR_AGENT_DIED, L"agent died");
++            } else if (waitRet == WAIT_TIMEOUT) {
++                throw LibWinptyException(WINPTY_ERROR_AGENT_TIMEOUT,
++                                      L"agent timed out");
++            } else if (waitRet == WAIT_FAILED) {
++                throwWindowsError(L"WaitForMultipleObjects failed");
++            } else {
++                ASSERT(false &&
++                    "unexpected WaitForMultipleObjects return value");
++            }
++        }
++        std::tie(success, lastError) = io.waitForCompletion(actual);
++    }
++}
++
++static void handlePendingIo(winpty_t &wp, OVERLAPPED &over, BOOL &success,
++                            DWORD &lastError) {
++    DWORD actual = 0;
++    handlePendingIo(wp, over, success, lastError, actual);
++}
++
++static void handleReadWriteErrors(winpty_t &wp, BOOL success, DWORD lastError,
++                                  const wchar_t *genericErrMsg) {
++    if (!success) {
++        // If the pipe connection is broken after it's been connected, then
++        // later I/O operations fail with ERROR_BROKEN_PIPE (reads) or
++        // ERROR_NO_DATA (writes).  With Wine, they may also fail with
++        // ERROR_PIPE_NOT_CONNECTED.  See this gist[1].
++        //
++        // [1] https://gist.github.com/rprichard/8dd8ca134b39534b7da2733994aa07ba
++        if (lastError == ERROR_BROKEN_PIPE || lastError == ERROR_NO_DATA ||
++                lastError == ERROR_PIPE_NOT_CONNECTED) {
++            throw LibWinptyException(WINPTY_ERROR_LOST_CONNECTION,
++                L"lost connection to agent");
++        } else {
++            throwWindowsError(genericErrMsg, lastError);
++        }
++    }
++}
++
++// Calls ConnectNamedPipe to wait until the agent connects to the control pipe.
++static void
++connectControlPipe(winpty_t &wp) {
++    OVERLAPPED over = {};
++    over.hEvent = wp.ioEvent.get();
++    BOOL success = ConnectNamedPipe(wp.controlPipe.get(), &over);
++    DWORD lastError = GetLastError();
++    handlePendingIo(wp, over, success, lastError);
++    if (!success && lastError == ERROR_PIPE_CONNECTED) {
++        success = TRUE;
++    }
++    if (!success) {
++        throwWindowsError(L"ConnectNamedPipe failed", lastError);
++    }
++}
++
++static void writeData(winpty_t &wp, const void *data, size_t amount) {
++    // Perform a single pipe write.
++    DWORD actual = 0;
++    OVERLAPPED over = {};
++    over.hEvent = wp.ioEvent.get();
++    BOOL success = WriteFile(wp.controlPipe.get(), data, amount,
++                             &actual, &over);
++    DWORD lastError = GetLastError();
++    if (!success) {
++        handlePendingIo(wp, over, success, lastError, actual);
++        handleReadWriteErrors(wp, success, lastError, L"WriteFile failed");
++        ASSERT(success);
++    }
++    // TODO: Can a partial write actually happen somehow?
++    ASSERT(actual == amount && "WriteFile wrote fewer bytes than requested");
++}
++
++static inline WriteBuffer newPacket() {
++    WriteBuffer packet;
++    packet.putRawValue<uint64_t>(0); // Reserve space for size.
++    return packet;
++}
++
++static void writePacket(winpty_t &wp, WriteBuffer &packet) {
++    const auto &buf = packet.buf();
++    packet.replaceRawValue<uint64_t>(0, buf.size());
++    writeData(wp, buf.data(), buf.size());
++}
++
++static size_t readData(winpty_t &wp, void *data, size_t amount) {
++    DWORD actual = 0;
++    OVERLAPPED over = {};
++    over.hEvent = wp.ioEvent.get();
++    BOOL success = ReadFile(wp.controlPipe.get(), data, amount,
++                            &actual, &over);
++    DWORD lastError = GetLastError();
++    if (!success) {
++        handlePendingIo(wp, over, success, lastError, actual);
++        handleReadWriteErrors(wp, success, lastError, L"ReadFile failed");
++    }
++    return actual;
++}
++
++static void readAll(winpty_t &wp, void *data, size_t amount) {
++    while (amount > 0) {
++        const size_t chunk = readData(wp, data, amount);
++        ASSERT(chunk <= amount && "readData result is larger than amount");
++        data = reinterpret_cast<char*>(data) + chunk;
++        amount -= chunk;
++    }
++}
++
++static uint64_t readUInt64(winpty_t &wp) {
++    uint64_t ret = 0;
++    readAll(wp, &ret, sizeof(ret));
++    return ret;
++}
++
++// Returns a reply packet's payload.
++static ReadBuffer readPacket(winpty_t &wp) {
++    const uint64_t packetSize = readUInt64(wp);
++    if (packetSize < sizeof(packetSize) || packetSize > SIZE_MAX) {
++        throwWinptyException(L"Agent RPC error: invalid packet size");
++    }
++    const size_t payloadSize = packetSize - sizeof(packetSize);
++    std::vector<char> bytes(payloadSize);
++    readAll(wp, bytes.data(), bytes.size());
++    return ReadBuffer(std::move(bytes));
++}
++
++static OwnedHandle createControlPipe(const std::wstring &name) {
++    const auto sd = createPipeSecurityDescriptorOwnerFullControl();
++    if (!sd) {
++        throwWinptyException(
++            L"could not create the control pipe's SECURITY_DESCRIPTOR");
++    }
++    SECURITY_ATTRIBUTES sa = {};
++    sa.nLength = sizeof(sa);
++    sa.lpSecurityDescriptor = sd.get();
++    HANDLE ret = CreateNamedPipeW(name.c_str(),
++        /*dwOpenMode=*/
++        PIPE_ACCESS_DUPLEX |
++            FILE_FLAG_FIRST_PIPE_INSTANCE |
++            FILE_FLAG_OVERLAPPED,
++        /*dwPipeMode=*/rejectRemoteClientsPipeFlag(),
++        /*nMaxInstances=*/1,
++        /*nOutBufferSize=*/8192,
++        /*nInBufferSize=*/256,
++        /*nDefaultTimeOut=*/30000,
++        &sa);
++    if (ret == INVALID_HANDLE_VALUE) {
++        throwWindowsError(L"CreateNamedPipeW failed");
++    }
++    return OwnedHandle(ret);
++}
++
++
++
++/*****************************************************************************
++ * Start the agent. */
++
++static OwnedHandle createEvent() {
++    // manual reset, initially unset
++    HANDLE h = CreateEventW(nullptr, TRUE, FALSE, nullptr);
++    if (h == nullptr) {
++        throwWindowsError(L"CreateEventW failed");
++    }
++    return OwnedHandle(h);
++}
++
++// For debugging purposes, provide a way to keep the console on the main window
++// station, visible.
++static bool shouldShowConsoleWindow() {
++    char buf[32];
++    return GetEnvironmentVariableA("WINPTY_SHOW_CONSOLE", buf, sizeof(buf)) > 0;
++}
++
++static bool shouldCreateBackgroundDesktop(bool &createUsingAgent) {
++    // Prior to Windows 7, winpty's repeated selection-deselection loop
++    // prevented the user from interacting with their *visible* console
++    // windows, unless we placed the console onto a background desktop.
++    // The SetProcessWindowStation call interferes with the clipboard and
++    // isn't thread-safe, though[1].  The call should perhaps occur in a
++    // special agent subprocess.  Spawning a process in a background desktop
++    // also breaks ConEmu, but marking the process SW_HIDE seems to correct
++    // that[2].
++    //
++    // Windows 7 moved a lot of console handling out of csrss.exe and into
++    // a per-console conhost.exe process, which may explain why it isn't
++    // affected.
++    //
++    // This is a somewhat risky change, so there are low-level flags to
++    // assist in debugging if there are issues.
++    //
++    // [1] https://github.com/rprichard/winpty/issues/58
++    // [2] https://github.com/rprichard/winpty/issues/70
++    bool ret = !shouldShowConsoleWindow() && !isAtLeastWindows7();
++    const bool force = hasDebugFlag("force_desktop");
++    const bool force_spawn = hasDebugFlag("force_desktop_spawn");
++    const bool force_curproc = hasDebugFlag("force_desktop_curproc");
++    const bool suppress = hasDebugFlag("no_desktop");
++    if (force + force_spawn + force_curproc + suppress > 1) {
++        trace("error: Only one of force_desktop, force_desktop_spawn, "
++              "force_desktop_curproc, and no_desktop may be set");
++    } else if (force) {
++        ret = true;
++    } else if (force_spawn) {
++        ret = true;
++        createUsingAgent = true;
++    } else if (force_curproc) {
++        ret = true;
++        createUsingAgent = false;
++    } else if (suppress) {
++        ret = false;
++    }
++    return ret;
++}
++
++static bool shouldSpecifyHideFlag() {
++    const bool force = hasDebugFlag("force_sw_hide");
++    const bool suppress = hasDebugFlag("no_sw_hide");
++    bool ret = !shouldShowConsoleWindow();
++    if (force && suppress) {
++        trace("error: Both the force_sw_hide and no_sw_hide flags are set");
++    } else if (force) {
++        ret = true;
++    } else if (suppress) {
++        ret = false;
++    }
++    return ret;
++}
++
++static OwnedHandle startAgentProcess(
++        const std::wstring &desktop,
++        const std::wstring &controlPipeName,
++        const std::wstring &params,
++        DWORD creationFlags,
++        DWORD &agentPid) {
++    const std::wstring exePath = findAgentProgram();
++    const std::wstring cmdline =
++        (WStringBuilder(256)
++            << L"\"" << exePath << L"\" "
++            << controlPipeName << L' '
++            << params).str_moved();
++
++    auto cmdlineV = vectorWithNulFromString(cmdline);
++    auto desktopV = vectorWithNulFromString(desktop);
++
++    // Start the agent.
++    STARTUPINFOW sui = {};
++    sui.cb = sizeof(sui);
++    sui.lpDesktop = desktop.empty() ? nullptr : desktopV.data();
++
++    if (shouldSpecifyHideFlag()) {
++        sui.dwFlags |= STARTF_USESHOWWINDOW;
++        sui.wShowWindow = SW_HIDE;
++    }
++    PROCESS_INFORMATION pi = {};
++    const BOOL success =
++        CreateProcessW(exePath.c_str(),
++                       cmdlineV.data(),
++                       nullptr, nullptr,
++                       /*bInheritHandles=*/FALSE,
++                       /*dwCreationFlags=*/creationFlags,
++                       nullptr, nullptr,
++                       &sui, &pi);
++    if (!success) {
++        const DWORD lastError = GetLastError();
++        const auto errStr =
++            (WStringBuilder(256)
++                << L"winpty-agent CreateProcess failed: cmdline='" << cmdline
++                << L"' err=0x" << whexOfInt(lastError)).str_moved();
++        throw LibWinptyException(
++            WINPTY_ERROR_AGENT_CREATION_FAILED, errStr.c_str());
++    }
++    CloseHandle(pi.hThread);
++    TRACE("Created agent successfully, pid=%u, cmdline=%s",
++          static_cast<unsigned int>(pi.dwProcessId),
++          utf8FromWide(cmdline).c_str());
++    agentPid = pi.dwProcessId;
++    return OwnedHandle(pi.hProcess);
++}
++
++static void verifyPipeClientPid(HANDLE serverPipe, DWORD agentPid) {
++    const auto client = getNamedPipeClientProcessId(serverPipe);
++    const auto success = std::get<0>(client);
++    const auto lastError = std::get<2>(client);
++    if (success == GetNamedPipeClientProcessId_Result::Success) {
++        const auto clientPid = std::get<1>(client);
++        if (clientPid != agentPid) {
++            WStringBuilder errMsg;
++            errMsg << L"Security check failed: pipe client pid (" << clientPid
++                   << L") does not match agent pid (" << agentPid << L")";
++            throwWinptyException(errMsg.c_str());
++        }
++    } else if (success == GetNamedPipeClientProcessId_Result::UnsupportedOs) {
++        trace("Pipe client PID security check skipped: "
++            "GetNamedPipeClientProcessId unsupported on this OS version");
++    } else {
++        throwWindowsError(L"GetNamedPipeClientProcessId failed", lastError);
++    }
++}
++
++static std::unique_ptr<winpty_t>
++createAgentSession(const winpty_config_t *cfg,
++                   const std::wstring &desktop,
++                   const std::wstring &params,
++                   DWORD creationFlags) {
++    std::unique_ptr<winpty_t> wp(new winpty_t);
++    wp->agentTimeoutMs = cfg->timeoutMs;
++    wp->ioEvent = createEvent();
++
++    // Create control server pipe.
++    const auto pipeName =
++        L"\\\\.\\pipe\\winpty-control-" + GenRandom().uniqueName();
++    wp->controlPipe = createControlPipe(pipeName);
++
++    DWORD agentPid = 0;
++    wp->agentProcess = startAgentProcess(
++        desktop, pipeName, params, creationFlags, agentPid);
++    connectControlPipe(*wp.get());
++    verifyPipeClientPid(wp->controlPipe.get(), agentPid);
++
++    return std::move(wp);
++}
++
++namespace {
++
++class AgentDesktop {
++public:
++    virtual std::wstring name() = 0;
++    virtual ~AgentDesktop() {}
++};
++
++class AgentDesktopDirect : public AgentDesktop {
++public:
++    AgentDesktopDirect(BackgroundDesktop &&desktop) :
++        m_desktop(std::move(desktop))
++    {
++    }
++    std::wstring name() override { return m_desktop.desktopName(); }
++private:
++    BackgroundDesktop m_desktop;
++};
++
++class AgentDesktopIndirect : public AgentDesktop {
++public:
++    AgentDesktopIndirect(std::unique_ptr<winpty_t> &&wp,
++                         std::wstring &&desktopName) :
++        m_wp(std::move(wp)),
++        m_desktopName(std::move(desktopName))
++    {
++    }
++    std::wstring name() override { return m_desktopName; }
++private:
++    std::unique_ptr<winpty_t> m_wp;
++    std::wstring m_desktopName;
++};
++
++} // anonymous namespace
++
++std::unique_ptr<AgentDesktop>
++setupBackgroundDesktop(const winpty_config_t *cfg) {
++    bool useDesktopAgent =
++        !(cfg->flags & WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION);
++    const bool useDesktop = shouldCreateBackgroundDesktop(useDesktopAgent);
++
++    if (!useDesktop) {
++        return std::unique_ptr<AgentDesktop>();
++    }
++
++    if (useDesktopAgent) {
++        auto wp = createAgentSession(
++            cfg, std::wstring(), L"--create-desktop", DETACHED_PROCESS);
++
++        // Read the desktop name.
++        auto packet = readPacket(*wp.get());
++        auto desktopName = packet.getWString();
++        packet.assertEof();
++
++        if (desktopName.empty()) {
++            return std::unique_ptr<AgentDesktop>();
++        } else {
++            return std::unique_ptr<AgentDesktop>(
++                new AgentDesktopIndirect(std::move(wp),
++                                         std::move(desktopName)));
++        }
++    } else {
++        try {
++            BackgroundDesktop desktop;
++            return std::unique_ptr<AgentDesktop>(new AgentDesktopDirect(
++                std::move(desktop)));
++        } catch (const WinptyException &e) {
++            trace("Error: failed to create background desktop, "
++                  "using original desktop instead: %s",
++                  utf8FromWide(e.what()).c_str());
++            return std::unique_ptr<AgentDesktop>();
++        }
++    }
++}
++
++WINPTY_API winpty_t *
++winpty_open(const winpty_config_t *cfg,
++            winpty_error_ptr_t *err /*OPTIONAL*/) {
++    API_TRY {
++        ASSERT(cfg != nullptr);
++        dumpWindowsVersion();
++        dumpVersionToTrace();
++
++        // Setup a background desktop for the agent.
++        auto desktop = setupBackgroundDesktop(cfg);
++        const auto desktopName = desktop ? desktop->name() : std::wstring();
++
++        // Start the primary agent session.
++        const auto params =
++            (WStringBuilder(128)
++                << cfg->flags << L' '
++                << cfg->mouseMode << L' '
++                << cfg->cols << L' '
++                << cfg->rows).str_moved();
++        auto wp = createAgentSession(cfg, desktopName, params,
++                                     CREATE_NEW_CONSOLE);
++
++        // Close handles to the background desktop and restore the original
++        // window station.  This must wait until we know the agent is running
++        // -- if we close these handles too soon, then the desktop and
++        // windowstation will be destroyed before the agent can connect with
++        // them.
++        //
++        // If we used a separate agent process to create the desktop, we
++        // disconnect from that process here, allowing it to exit.
++        desktop.reset();
++
++        // If we ran the agent process on a background desktop, then when we
++        // spawn a child process from the agent, it will need to be explicitly
++        // placed back onto the original desktop.
++        if (!desktopName.empty()) {
++            wp->spawnDesktopName = getCurrentDesktopName();
++        }
++
++        // Get the CONIN/CONOUT pipe names.
++        auto packet = readPacket(*wp.get());
++        wp->coninPipeName = packet.getWString();
++        wp->conoutPipeName = packet.getWString();
++        if (cfg->flags & WINPTY_FLAG_CONERR) {
++            wp->conerrPipeName = packet.getWString();
++        }
++        packet.assertEof();
++
++        return wp.release();
++    } API_CATCH(nullptr)
++}
++
++WINPTY_API HANDLE winpty_agent_process(winpty_t *wp) {
++    ASSERT(wp != nullptr);
++    return wp->agentProcess.get();
++}
++
++
++
++/*****************************************************************************
++ * I/O pipes. */
++
++static const wchar_t *cstrFromWStringOrNull(const std::wstring &str) {
++    try {
++        return str.c_str();
++    } catch (const std::bad_alloc&) {
++        return nullptr;
++    }
++}
++
++WINPTY_API LPCWSTR winpty_conin_name(winpty_t *wp) {
++    ASSERT(wp != nullptr);
++    return cstrFromWStringOrNull(wp->coninPipeName);
++}
++
++WINPTY_API LPCWSTR winpty_conout_name(winpty_t *wp) {
++    ASSERT(wp != nullptr);
++    return cstrFromWStringOrNull(wp->conoutPipeName);
++}
++
++WINPTY_API LPCWSTR winpty_conerr_name(winpty_t *wp) {
++    ASSERT(wp != nullptr);
++    if (wp->conerrPipeName.empty()) {
++        return nullptr;
++    } else {
++        return cstrFromWStringOrNull(wp->conerrPipeName);
++    }
++}
++
++
++
++/*****************************************************************************
++ * winpty agent RPC calls. */
++
++namespace {
++
++// Close the control pipe if something goes wrong with the pipe communication,
++// which could leave the control pipe in an inconsistent state.
++class RpcOperation {
++public:
++    RpcOperation(winpty_t &wp) : m_wp(wp) {
++        if (m_wp.controlPipe.get() == nullptr) {
++            throwWinptyException(L"Agent shutdown due to RPC failure");
++        }
++    }
++    ~RpcOperation() {
++        if (!m_success) {
++            trace("~RpcOperation: Closing control pipe");
++            m_wp.controlPipe.dispose(true);
++        }
++    }
++    void success() { m_success = true; }
++private:
++    winpty_t &m_wp;
++    bool m_success = false;
++};
++
++} // anonymous namespace
++
++
++
++/*****************************************************************************
++ * winpty agent RPC call: process creation. */
++
++// Return a std::wstring containing every character of the environment block.
++// Typically, the block is non-empty, so the std::wstring returned ends with
++// two NUL terminators.  (These two terminators are counted in size(), so
++// calling c_str() produces a triply-terminated string.)
++static std::wstring wstringFromEnvBlock(const wchar_t *env) {
++    std::wstring envStr;
++    if (env != NULL) {
++        const wchar_t *p = env;
++        while (*p != L'\0') {
++            p += wcslen(p) + 1;
++        }
++        p++;
++        envStr.assign(env, p);
++
++        // Assuming the environment was non-empty, envStr now ends with two NUL
++        // terminators.
++        //
++        // If the environment were empty, though, then envStr would only be
++        // singly terminated, but the MSDN documentation thinks an env block is
++        // always doubly-terminated, so add an extra NUL just in case it
++        // matters.
++        const auto envStrSz = envStr.size();
++        if (envStrSz == 1) {
++            ASSERT(envStr[0] == L'\0');
++            envStr.push_back(L'\0');
++        } else {
++            ASSERT(envStrSz >= 3);
++            ASSERT(envStr[envStrSz - 3] != L'\0');
++            ASSERT(envStr[envStrSz - 2] == L'\0');
++            ASSERT(envStr[envStrSz - 1] == L'\0');
++        }
++    }
++    return envStr;
++}
++
++WINPTY_API winpty_spawn_config_t *
++winpty_spawn_config_new(UINT64 winptyFlags,
++                        LPCWSTR appname /*OPTIONAL*/,
++                        LPCWSTR cmdline /*OPTIONAL*/,
++                        LPCWSTR cwd /*OPTIONAL*/,
++                        LPCWSTR env /*OPTIONAL*/,
++                        winpty_error_ptr_t *err /*OPTIONAL*/) {
++    API_TRY {
++        ASSERT((winptyFlags & WINPTY_SPAWN_FLAG_MASK) == winptyFlags);
++        std::unique_ptr<winpty_spawn_config_t> cfg(new winpty_spawn_config_t);
++        cfg->winptyFlags = winptyFlags;
++        if (appname != nullptr) { cfg->appname = appname; }
++        if (cmdline != nullptr) { cfg->cmdline = cmdline; }
++        if (cwd != nullptr) { cfg->cwd = cwd; }
++        if (env != nullptr) { cfg->env = wstringFromEnvBlock(env); }
++        return cfg.release();
++    } API_CATCH(nullptr)
++}
++
++WINPTY_API void winpty_spawn_config_free(winpty_spawn_config_t *cfg) {
++    delete cfg;
++}
++
++// It's safe to truncate a handle from 64-bits to 32-bits, or to sign-extend it
++// back to 64-bits.  See the MSDN article, "Interprocess Communication Between
++// 32-bit and 64-bit Applications".
++// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203.aspx
++static inline HANDLE handleFromInt64(int64_t i) {
++    return reinterpret_cast<HANDLE>(static_cast<intptr_t>(i));
++}
++
++// Given a process and a handle in that process, duplicate the handle into the
++// current process and close it in the originating process.
++static inline OwnedHandle stealHandle(HANDLE process, HANDLE handle) {
++    HANDLE result = nullptr;
++    if (!DuplicateHandle(process, handle,
++            GetCurrentProcess(),
++            &result, 0, FALSE,
++            DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
++        throwWindowsError(L"DuplicateHandle of process handle");
++    }
++    return OwnedHandle(result);
++}
++
++WINPTY_API BOOL
++winpty_spawn(winpty_t *wp,
++             const winpty_spawn_config_t *cfg,
++             HANDLE *process_handle /*OPTIONAL*/,
++             HANDLE *thread_handle /*OPTIONAL*/,
++             DWORD *create_process_error /*OPTIONAL*/,
++             winpty_error_ptr_t *err /*OPTIONAL*/) {
++    API_TRY {
++        ASSERT(wp != nullptr && cfg != nullptr);
++
++        if (process_handle != nullptr) { *process_handle = nullptr; }
++        if (thread_handle != nullptr) { *thread_handle = nullptr; }
++        if (create_process_error != nullptr) { *create_process_error = 0; }
++
++        LockGuard<Mutex> lock(wp->mutex);
++        RpcOperation rpc(*wp);
++
++        // Send spawn request.
++        auto packet = newPacket();
++        packet.putInt32(AgentMsg::StartProcess);
++        packet.putInt64(cfg->winptyFlags);
++        packet.putInt32(process_handle != nullptr);
++        packet.putInt32(thread_handle != nullptr);
++        packet.putWString(cfg->appname);
++        packet.putWString(cfg->cmdline);
++        packet.putWString(cfg->cwd);
++        packet.putWString(cfg->env);
++        packet.putWString(wp->spawnDesktopName);
++        writePacket(*wp, packet);
++
++        // Receive reply.
++        auto reply = readPacket(*wp);
++        const auto result = static_cast<StartProcessResult>(reply.getInt32());
++        if (result == StartProcessResult::CreateProcessFailed) {
++            const DWORD lastError = reply.getInt32();
++            reply.assertEof();
++            if (create_process_error != nullptr) {
++                *create_process_error = lastError;
++            }
++            rpc.success();
++            throw LibWinptyException(WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED,
++                L"CreateProcess failed");
++        } else if (result == StartProcessResult::ProcessCreated) {
++            const HANDLE remoteProcess = handleFromInt64(reply.getInt64());
++            const HANDLE remoteThread = handleFromInt64(reply.getInt64());
++            reply.assertEof();
++            OwnedHandle localProcess;
++            OwnedHandle localThread;
++            if (remoteProcess != nullptr) {
++                localProcess =
++                    stealHandle(wp->agentProcess.get(), remoteProcess);
++            }
++            if (remoteThread != nullptr) {
++                localThread =
++                    stealHandle(wp->agentProcess.get(), remoteThread);
++            }
++            if (process_handle != nullptr) {
++                *process_handle = localProcess.release();
++            }
++            if (thread_handle != nullptr) {
++                *thread_handle = localThread.release();
++            }
++            rpc.success();
++        } else {
++            throwWinptyException(
++                L"Agent RPC error: invalid StartProcessResult");
++        }
++        return TRUE;
++    } API_CATCH(FALSE)
++}
++
++
++
++/*****************************************************************************
++ * winpty agent RPC calls: everything else */
++
++WINPTY_API BOOL
++winpty_set_size(winpty_t *wp, int cols, int rows,
++                winpty_error_ptr_t *err /*OPTIONAL*/) {
++    API_TRY {
++        ASSERT(wp != nullptr && cols > 0 && rows > 0);
++        LockGuard<Mutex> lock(wp->mutex);
++        RpcOperation rpc(*wp);
++        auto packet = newPacket();
++        packet.putInt32(AgentMsg::SetSize);
++        packet.putInt32(cols);
++        packet.putInt32(rows);
++        writePacket(*wp, packet);
++        readPacket(*wp).assertEof();
++        rpc.success();
++        return TRUE;
++    } API_CATCH(FALSE)
++}
++
++WINPTY_API int
++winpty_get_console_process_list(winpty_t *wp, int *processList, const int processCount,
++                                winpty_error_ptr_t *err /*OPTIONAL*/) {
++    API_TRY {
++        ASSERT(wp != nullptr);
++        ASSERT(processList != nullptr);
++        LockGuard<Mutex> lock(wp->mutex);
++        RpcOperation rpc(*wp);
++        auto packet = newPacket();
++        packet.putInt32(AgentMsg::GetConsoleProcessList);
++        writePacket(*wp, packet);
++        auto reply = readPacket(*wp);
++
++        auto actualProcessCount = reply.getInt32();
++
++        if (actualProcessCount <= processCount) {
++            for (auto i = 0; i < actualProcessCount; i++) {
++                processList[i] = reply.getInt32();
++            }
++        }
++
++        reply.assertEof();
++        rpc.success();
++        return actualProcessCount;
++    } API_CATCH(0)
++}
++
++WINPTY_API void winpty_free(winpty_t *wp) {
++    // At least in principle, CloseHandle can fail, so this deletion can
++    // fail.  It won't throw an exception, but maybe there's an error that
++    // should be propagated?
++    delete wp;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ab60c6b9619f2496e9427d929949c935a054e1bd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,38 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_AGENT_MSG_H
++#define WINPTY_SHARED_AGENT_MSG_H
++
++struct AgentMsg
++{
++    enum Type {
++        StartProcess,
++        SetSize,
++        GetConsoleProcessList,
++    };
++};
++
++enum class StartProcessResult {
++    CreateProcessFailed,
++    ProcessCreated,
++};
++
++#endif // WINPTY_SHARED_AGENT_MSG_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1bea7e53dd4d592ca46eeafbe773b314ddc55693
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,122 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "BackgroundDesktop.h"
++
++#include <memory>
++
++#include "DebugClient.h"
++#include "StringUtil.h"
++#include "WinptyException.h"
++
++namespace {
++
++static std::wstring getObjectName(HANDLE object) {
++    BOOL success;
++    DWORD lengthNeeded = 0;
++    GetUserObjectInformationW(object, UOI_NAME,
++                              nullptr, 0,
++                              &lengthNeeded);
++    ASSERT(lengthNeeded % sizeof(wchar_t) == 0);
++    std::unique_ptr<wchar_t[]> tmp(
++        new wchar_t[lengthNeeded / sizeof(wchar_t)]);
++    success = GetUserObjectInformationW(object, UOI_NAME,
++                                        tmp.get(), lengthNeeded,
++                                        nullptr);
++    if (!success) {
++        throwWindowsError(L"GetUserObjectInformationW failed");
++    }
++    return std::wstring(tmp.get());
++}
++
++static std::wstring getDesktopName(HWINSTA winsta, HDESK desk) {
++    return getObjectName(winsta) + L"\\" + getObjectName(desk);
++}
++
++} // anonymous namespace
++
++// Get a non-interactive window station for the agent.
++// TODO: review security w.r.t. windowstation and desktop.
++BackgroundDesktop::BackgroundDesktop() {
++    try {
++        m_originalStation = GetProcessWindowStation();
++        if (m_originalStation == nullptr) {
++            throwWindowsError(
++                L"BackgroundDesktop ctor: "
++                L"GetProcessWindowStation returned NULL");
++        }
++        m_newStation =
++            CreateWindowStationW(nullptr, 0, WINSTA_ALL_ACCESS, nullptr);
++        if (m_newStation == nullptr) {
++            throwWindowsError(
++                L"BackgroundDesktop ctor: CreateWindowStationW returned NULL");
++        }
++        if (!SetProcessWindowStation(m_newStation)) {
++            throwWindowsError(
++                L"BackgroundDesktop ctor: SetProcessWindowStation failed");
++        }
++        m_newDesktop = CreateDesktopW(
++            L"Default", nullptr, nullptr, 0, GENERIC_ALL, nullptr);
++        if (m_newDesktop == nullptr) {
++            throwWindowsError(
++                L"BackgroundDesktop ctor: CreateDesktopW failed");
++        }
++        m_newDesktopName = getDesktopName(m_newStation, m_newDesktop);
++        TRACE("Created background desktop: %s",
++            utf8FromWide(m_newDesktopName).c_str());
++    } catch (...) {
++        dispose();
++        throw;
++    }
++}
++
++void BackgroundDesktop::dispose() WINPTY_NOEXCEPT {
++    if (m_originalStation != nullptr) {
++        SetProcessWindowStation(m_originalStation);
++        m_originalStation = nullptr;
++    }
++    if (m_newDesktop != nullptr) {
++        CloseDesktop(m_newDesktop);
++        m_newDesktop = nullptr;
++    }
++    if (m_newStation != nullptr) {
++        CloseWindowStation(m_newStation);
++        m_newStation = nullptr;
++    }
++}
++
++std::wstring getCurrentDesktopName() {
++    // MSDN says that the handles returned by GetProcessWindowStation and
++    // GetThreadDesktop do not need to be passed to CloseWindowStation and
++    // CloseDesktop, respectively.
++    const HWINSTA winsta = GetProcessWindowStation();
++    if (winsta == nullptr) {
++        throwWindowsError(
++            L"getCurrentDesktopName: "
++            L"GetProcessWindowStation returned NULL");
++    }
++    const HDESK desk = GetThreadDesktop(GetCurrentThreadId());
++    if (desk == nullptr) {
++        throwWindowsError(
++            L"getCurrentDesktopName: "
++            L"GetThreadDesktop returned NULL");
++    }
++    return getDesktopName(winsta, desk);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c692e57dc49a012a93701cb7af09244fafe8b02f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,73 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_BACKGROUND_DESKTOP_H
++#define WINPTY_SHARED_BACKGROUND_DESKTOP_H
++
++#include <windows.h>
++
++#include <string>
++
++#include "WinptyException.h"
++
++class BackgroundDesktop {
++public:
++    BackgroundDesktop();
++    ~BackgroundDesktop() { dispose(); }
++    void dispose() WINPTY_NOEXCEPT;
++    const std::wstring &desktopName() const { return m_newDesktopName; }
++
++    BackgroundDesktop(const BackgroundDesktop &other) = delete;
++    BackgroundDesktop &operator=(const BackgroundDesktop &other) = delete;
++
++    // We can't default the move constructor and assignment operator with
++    // MSVC 2013.  We *could* if we required at least MSVC 2015 to build.
++
++    BackgroundDesktop(BackgroundDesktop &&other) :
++            m_originalStation(other.m_originalStation),
++            m_newStation(other.m_newStation),
++            m_newDesktop(other.m_newDesktop),
++            m_newDesktopName(std::move(other.m_newDesktopName)) {
++        other.m_originalStation = nullptr;
++        other.m_newStation = nullptr;
++        other.m_newDesktop = nullptr;
++    }
++    BackgroundDesktop &operator=(BackgroundDesktop &&other) {
++        dispose();
++        m_originalStation = other.m_originalStation;
++        m_newStation = other.m_newStation;
++        m_newDesktop = other.m_newDesktop;
++        m_newDesktopName = std::move(other.m_newDesktopName);
++        other.m_originalStation = nullptr;
++        other.m_newStation = nullptr;
++        other.m_newDesktop = nullptr;
++        return *this;
++    }
++
++private:
++    HWINSTA m_originalStation = nullptr;
++    HWINSTA m_newStation = nullptr;
++    HDESK m_newDesktop = nullptr;
++    std::wstring m_newDesktopName;
++};
++
++std::wstring getCurrentDesktopName();
++
++#endif // WINPTY_SHARED_BACKGROUND_DESKTOP_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..158a629d564ba6f29afcfe8a89aa5c37f00a2b42
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,103 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Buffer.h"
++
++#include <stdint.h>
++
++#include "DebugClient.h"
++#include "WinptyAssert.h"
++
++// Define the READ_BUFFER_CHECK() macro.  It *must* evaluate its condition,
++// exactly once.
++#define READ_BUFFER_CHECK(cond)                                 \
++    do {                                                        \
++        if (!(cond)) {                                          \
++            trace("decode error: %s", #cond);                   \
++            throw DecodeError();                                \
++        }                                                       \
++    } while (false)
++
++enum class Piece : uint8_t { Int32, Int64, WString };
++
++void WriteBuffer::putRawData(const void *data, size_t len) {
++    const auto p = reinterpret_cast<const char*>(data);
++    m_buf.insert(m_buf.end(), p, p + len);
++}
++
++void WriteBuffer::replaceRawData(size_t pos, const void *data, size_t len) {
++    ASSERT(pos <= m_buf.size() && len <= m_buf.size() - pos);
++    const auto p = reinterpret_cast<const char*>(data);
++    std::copy(p, p + len, &m_buf[pos]);
++}
++
++void WriteBuffer::putInt32(int32_t i) {
++    putRawValue(Piece::Int32);
++    putRawValue(i);
++}
++
++void WriteBuffer::putInt64(int64_t i) {
++    putRawValue(Piece::Int64);
++    putRawValue(i);
++}
++
++// len is in characters, excluding NUL, i.e. the number of wchar_t elements
++void WriteBuffer::putWString(const wchar_t *str, size_t len) {
++    putRawValue(Piece::WString);
++    putRawValue(static_cast<uint64_t>(len));
++    putRawData(str, sizeof(wchar_t) * len);
++}
++
++void ReadBuffer::getRawData(void *data, size_t len) {
++    ASSERT(m_off <= m_buf.size());
++    READ_BUFFER_CHECK(len <= m_buf.size() - m_off);
++    const char *const inp = &m_buf[m_off];
++    std::copy(inp, inp + len, reinterpret_cast<char*>(data));
++    m_off += len;
++}
++
++int32_t ReadBuffer::getInt32() {
++    READ_BUFFER_CHECK(getRawValue<Piece>() == Piece::Int32);
++    return getRawValue<int32_t>();
++}
++
++int64_t ReadBuffer::getInt64() {
++    READ_BUFFER_CHECK(getRawValue<Piece>() == Piece::Int64);
++    return getRawValue<int64_t>();
++}
++
++std::wstring ReadBuffer::getWString() {
++    READ_BUFFER_CHECK(getRawValue<Piece>() == Piece::WString);
++    const uint64_t charLen = getRawValue<uint64_t>();
++    READ_BUFFER_CHECK(charLen <= SIZE_MAX / sizeof(wchar_t));
++    // To be strictly conforming, we can't use the convenient wstring
++    // constructor, because the string in m_buf mightn't be aligned.
++    std::wstring ret;
++    if (charLen > 0) {
++        const size_t byteLen = charLen * sizeof(wchar_t);
++        ret.resize(charLen);
++        getRawData(&ret[0], byteLen);
++    }
++    return ret;
++}
++
++void ReadBuffer::assertEof() {
++    READ_BUFFER_CHECK(m_off == m_buf.size());
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c2dd382e5b25e7227ec5982ecab5e22aa258c948
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,102 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_BUFFER_H
++#define WINPTY_SHARED_BUFFER_H
++
++#include <stdint.h>
++#include <string.h>
++
++#include <algorithm>
++#include <utility>
++#include <vector>
++#include <string>
++
++#include "WinptyException.h"
++
++class WriteBuffer {
++private:
++    std::vector<char> m_buf;
++
++public:
++    WriteBuffer() {}
++
++    template <typename T> void putRawValue(const T &t) {
++        putRawData(&t, sizeof(t));
++    }
++    template <typename T> void replaceRawValue(size_t pos, const T &t) {
++        replaceRawData(pos, &t, sizeof(t));
++    }
++
++    void putRawData(const void *data, size_t len);
++    void replaceRawData(size_t pos, const void *data, size_t len);
++    void putInt32(int32_t i);
++    void putInt64(int64_t i);
++    void putWString(const wchar_t *str, size_t len);
++    void putWString(const wchar_t *str)         { putWString(str, wcslen(str)); }
++    void putWString(const std::wstring &str)    { putWString(str.data(), str.size()); }
++    std::vector<char> &buf()                    { return m_buf; }
++
++    // MSVC 2013 does not generate these automatically, so help it out.
++    WriteBuffer(WriteBuffer &&other) : m_buf(std::move(other.m_buf)) {}
++    WriteBuffer &operator=(WriteBuffer &&other) {
++        m_buf = std::move(other.m_buf);
++        return *this;
++    }
++};
++
++class ReadBuffer {
++public:
++    class DecodeError : public WinptyException {
++        virtual const wchar_t *what() const WINPTY_NOEXCEPT override {
++            return L"DecodeError: RPC message decoding error";
++        }
++    };
++
++private:
++    std::vector<char> m_buf;
++    size_t m_off = 0;
++
++public:
++    explicit ReadBuffer(std::vector<char> &&buf) : m_buf(std::move(buf)) {}
++
++    template <typename T> T getRawValue() {
++        T ret = {};
++        getRawData(&ret, sizeof(ret));
++        return ret;
++    }
++
++    void getRawData(void *data, size_t len);
++    int32_t getInt32();
++    int64_t getInt64();
++    std::wstring getWString();
++    void assertEof();
++
++    // MSVC 2013 does not generate these automatically, so help it out.
++    ReadBuffer(ReadBuffer &&other) :
++        m_buf(std::move(other.m_buf)), m_off(other.m_off) {}
++    ReadBuffer &operator=(ReadBuffer &&other) {
++        m_buf = std::move(other.m_buf);
++        m_off = other.m_off;
++        return *this;
++    }
++};
++
++#endif // WINPTY_SHARED_BUFFER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..bafe0c89541b74af4c6b67870a5ffb7dc4825c12
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,187 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "DebugClient.h"
++
++#include <windows.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include <algorithm>
++#include <string>
++
++#include "winpty_snprintf.h"
++
++const wchar_t *const kPipeName = L"\\\\.\\pipe\\DebugServer";
++
++void *volatile g_debugConfig;
++
++namespace {
++
++// It would be easy to accidentally trample on the Windows LastError value
++// by adding logging/debugging code.  Ensure that can't happen by saving and
++// restoring the value.  This saving and restoring doesn't happen along the
++// fast path.
++class PreserveLastError {
++public:
++    PreserveLastError() : m_lastError(GetLastError()) {}
++    ~PreserveLastError() { SetLastError(m_lastError); }
++private:
++    DWORD m_lastError;
++};
++
++} // anonymous namespace
++
++static void sendToDebugServer(const char *message)
++{
++    HANDLE tracePipe = INVALID_HANDLE_VALUE;
++
++    do {
++        // The default impersonation level is SECURITY_IMPERSONATION, which allows
++        // a sufficiently authorized named pipe server to impersonate the client.
++        // There's no need for impersonation in this debugging system, so reduce
++        // the impersonation level to SECURITY_IDENTIFICATION, which allows a
++        // server to merely identify us.
++        tracePipe = CreateFileW(
++            kPipeName,
++            GENERIC_READ | GENERIC_WRITE,
++            0, NULL, OPEN_EXISTING,
++            SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
++            NULL);
++    } while (tracePipe == INVALID_HANDLE_VALUE &&
++             GetLastError() == ERROR_PIPE_BUSY &&
++             WaitNamedPipeW(kPipeName, NMPWAIT_WAIT_FOREVER));
++
++    if (tracePipe != INVALID_HANDLE_VALUE) {
++        DWORD newMode = PIPE_READMODE_MESSAGE;
++        SetNamedPipeHandleState(tracePipe, &newMode, NULL, NULL);
++        char response[16];
++        DWORD actual = 0;
++        TransactNamedPipe(tracePipe,
++            const_cast<char*>(message), strlen(message),
++            response, sizeof(response), &actual, NULL);
++        CloseHandle(tracePipe);
++    }
++}
++
++// Get the current UTC time as milliseconds from the epoch (ignoring leap
++// seconds).  Use the Unix epoch for consistency with DebugClient.py.  There
++// are 134774 days between 1601-01-01 (the Win32 epoch) and 1970-01-01 (the
++// Unix epoch).
++static long long unixTimeMillis()
++{
++    FILETIME fileTime;
++    GetSystemTimeAsFileTime(&fileTime);
++    long long msTime = (((long long)fileTime.dwHighDateTime << 32) +
++                       fileTime.dwLowDateTime) / 10000;
++    return msTime - 134774LL * 24 * 3600 * 1000;
++}
++
++static const char *getDebugConfig()
++{
++    if (g_debugConfig == NULL) {
++        PreserveLastError preserve;
++        const int bufSize = 256;
++        char buf[bufSize];
++        DWORD actualSize =
++            GetEnvironmentVariableA("WINPTY_DEBUG", buf, bufSize);
++        if (actualSize == 0 || actualSize >= static_cast<DWORD>(bufSize)) {
++            buf[0] = '\0';
++        }
++        const size_t len = strlen(buf) + 1;
++        char *newConfig = new char[len];
++        std::copy(buf, buf + len, newConfig);
++        void *oldValue = InterlockedCompareExchangePointer(
++            &g_debugConfig, newConfig, NULL);
++        if (oldValue != NULL) {
++            delete [] newConfig;
++        }
++    }
++    return static_cast<const char*>(g_debugConfig);
++}
++
++bool isTracingEnabled()
++{
++    static bool disabled, enabled;
++    if (disabled) {
++        return false;
++    } else if (enabled) {
++        return true;
++    } else {
++        // Recognize WINPTY_DEBUG=1 for backwards compatibility.
++        PreserveLastError preserve;
++        bool value = hasDebugFlag("trace") || hasDebugFlag("1");
++        disabled = !value;
++        enabled = value;
++        return value;
++    }
++}
++
++bool hasDebugFlag(const char *flag)
++{
++    if (strchr(flag, ',') != NULL) {
++        trace("INTERNAL ERROR: hasDebugFlag flag has comma: '%s'", flag);
++        abort();
++    }
++    const char *const configCStr = getDebugConfig();
++    if (configCStr[0] == '\0') {
++        return false;
++    }
++    PreserveLastError preserve;
++    std::string config(configCStr);
++    std::string flagStr(flag);
++    config = "," + config + ",";
++    flagStr = "," + flagStr + ",";
++    return config.find(flagStr) != std::string::npos;
++}
++
++void trace(const char *format, ...)
++{
++    if (!isTracingEnabled())
++        return;
++
++    PreserveLastError preserve;
++    char message[1024];
++
++    va_list ap;
++    va_start(ap, format);
++    winpty_vsnprintf(message, format, ap);
++    message[sizeof(message) - 1] = '\0';
++    va_end(ap);
++
++    const int currentTime = (int)(unixTimeMillis() % (100000 * 1000));
++
++    char moduleName[1024];
++    moduleName[0] = '\0';
++    GetModuleFileNameA(NULL, moduleName, sizeof(moduleName));
++    const char *baseName = strrchr(moduleName, '\\');
++    baseName = (baseName != NULL) ? baseName + 1 : moduleName;
++
++    char fullMessage[1024];
++    winpty_snprintf(fullMessage,
++             "[%05d.%03d %s,p%04d,t%04d]: %s",
++             currentTime / 1000, currentTime % 1000,
++             baseName, (int)GetCurrentProcessId(), (int)GetCurrentThreadId(),
++             message);
++    fullMessage[sizeof(fullMessage) - 1] = '\0';
++
++    sendToDebugServer(fullMessage);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b1260711301100db2c534839c69205e85fc06dd3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,38 @@@
++// Copyright (c) 2011-2012 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef DEBUGCLIENT_H
++#define DEBUGCLIENT_H
++
++#include "winpty_snprintf.h"
++
++bool isTracingEnabled();
++bool hasDebugFlag(const char *flag);
++void trace(const char *format, ...) WINPTY_SNPRINTF_FORMAT(1, 2);
++
++// This macro calls trace without evaluating the arguments.
++#define TRACE(format, ...)                          \
++    do {                                            \
++        if (isTracingEnabled()) {                   \
++            trace((format), ## __VA_ARGS__);        \
++        }                                           \
++    } while (false)
++
++#endif // DEBUGCLIENT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6d7920643afc65e56ac863f2c880344b0307ae8f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,138 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "GenRandom.h"
++
++#include <stdint.h>
++#include <string.h>
++
++#include "DebugClient.h"
++#include "StringBuilder.h"
++
++static volatile LONG g_pipeCounter;
++
++GenRandom::GenRandom() : m_advapi32(L"advapi32.dll") {
++    // First try to use the pseudo-documented RtlGenRandom function from
++    // advapi32.dll.  Creating a CryptoAPI context is slow, and RtlGenRandom
++    // avoids the overhead.  It's documented in this blog post[1] and on
++    // MSDN[2] with a disclaimer about future breakage.  This technique is
++    // apparently built-in into the MSVC CRT, though, for the rand_s function,
++    // so perhaps it is stable enough.
++    //
++    // [1] http://blogs.msdn.com/b/michael_howard/archive/2005/01/14/353379.aspx
++    // [2] https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694(v=vs.85).aspx
++    //
++    // Both RtlGenRandom and the Crypto API functions exist in XP and up.
++    m_rtlGenRandom = reinterpret_cast<RtlGenRandom_t*>(
++        m_advapi32.proc("SystemFunction036"));
++    // The OsModule class logs an error message if the proc is nullptr.
++    if (m_rtlGenRandom != nullptr) {
++        return;
++    }
++
++    // Fall back to the crypto API.
++    m_cryptProvIsValid =
++        CryptAcquireContext(&m_cryptProv, nullptr, nullptr,
++                            PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) != 0;
++    if (!m_cryptProvIsValid) {
++        trace("GenRandom: CryptAcquireContext failed: %u",
++            static_cast<unsigned>(GetLastError()));
++    }
++}
++
++GenRandom::~GenRandom() {
++    if (m_cryptProvIsValid) {
++        CryptReleaseContext(m_cryptProv, 0);
++    }
++}
++
++// Returns false if the context is invalid or the generation fails.
++bool GenRandom::fillBuffer(void *buffer, size_t size) {
++    memset(buffer, 0, size);
++    bool success = false;
++    if (m_rtlGenRandom != nullptr) {
++        success = m_rtlGenRandom(buffer, size) != 0;
++        if (!success) {
++            trace("GenRandom: RtlGenRandom/SystemFunction036 failed: %u",
++                static_cast<unsigned>(GetLastError()));
++        }
++    } else if (m_cryptProvIsValid) {
++        success =
++            CryptGenRandom(m_cryptProv, size,
++                           reinterpret_cast<BYTE*>(buffer)) != 0;
++        if (!success) {
++            trace("GenRandom: CryptGenRandom failed, size=%d, lasterror=%u",
++                static_cast<int>(size),
++                static_cast<unsigned>(GetLastError()));
++        }
++    }
++    return success;
++}
++
++// Returns an empty string if either of CryptAcquireContext or CryptGenRandom
++// fail.
++std::string GenRandom::randomBytes(size_t numBytes) {
++    std::string ret(numBytes, '\0');
++    if (!fillBuffer(&ret[0], numBytes)) {
++        return std::string();
++    }
++    return ret;
++}
++
++std::wstring GenRandom::randomHexString(size_t numBytes) {
++    const std::string bytes = randomBytes(numBytes);
++    std::wstring ret(bytes.size() * 2, L'\0');
++    for (size_t i = 0; i < bytes.size(); ++i) {
++        static const wchar_t hex[] = L"0123456789abcdef";
++        ret[i * 2]     = hex[static_cast<uint8_t>(bytes[i]) >> 4];
++        ret[i * 2 + 1] = hex[static_cast<uint8_t>(bytes[i]) & 0xF];
++    }
++    return ret;
++}
++
++// Returns a 64-bit value representing the number of 100-nanosecond intervals
++// since January 1, 1601.
++static uint64_t systemTimeAsUInt64() {
++    FILETIME monotonicTime = {};
++    GetSystemTimeAsFileTime(&monotonicTime);
++    return (static_cast<uint64_t>(monotonicTime.dwHighDateTime) << 32) |
++            static_cast<uint64_t>(monotonicTime.dwLowDateTime);
++}
++
++// Generates a unique and hard-to-guess case-insensitive string suitable for
++// use in a pipe filename or a Windows object name.
++std::wstring GenRandom::uniqueName() {
++    // First include enough information to avoid collisions assuming
++    // cooperative software.  This code assumes that a process won't die and
++    // be replaced with a recycled PID within a single GetSystemTimeAsFileTime
++    // interval.
++    WStringBuilder sb(64);
++    sb << GetCurrentProcessId()
++       << L'-' << InterlockedIncrement(&g_pipeCounter)
++       << L'-' << whexOfInt(systemTimeAsUInt64());
++    // It isn't clear to me how the crypto APIs would fail.  It *probably*
++    // doesn't matter that much anyway?  In principle, a predictable pipe name
++    // is subject to a local denial-of-service attack.
++    auto random = randomHexString(16);
++    if (!random.empty()) {
++        sb << L'-' << random;
++    }
++    return sb.str_moved();
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..746cb1ecf701b140015d1f101ad5bdb39b590715
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,55 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_GEN_RANDOM_H
++#define WINPTY_GEN_RANDOM_H
++
++// The original MinGW requires that we include wincrypt.h.  With MinGW-w64 and
++// MSVC, including windows.h is sufficient.
++#include <windows.h>
++#include <wincrypt.h>
++
++#include <string>
++
++#include "OsModule.h"
++
++class GenRandom {
++    typedef BOOLEAN WINAPI RtlGenRandom_t(PVOID, ULONG);
++
++    OsModule m_advapi32;
++    RtlGenRandom_t *m_rtlGenRandom = nullptr;
++    bool m_cryptProvIsValid = false;
++    HCRYPTPROV m_cryptProv = 0;
++
++public:
++    GenRandom();
++    ~GenRandom();
++    bool fillBuffer(void *buffer, size_t size);
++    std::string randomBytes(size_t numBytes);
++    std::wstring randomHexString(size_t numBytes);
++    std::wstring uniqueName();
++
++    // Return true if the crypto context was successfully initialized.
++    bool valid() const {
++        return m_rtlGenRandom != nullptr || m_cryptProvIsValid;
++    }
++};
++
++#endif // WINPTY_GEN_RANDOM_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a9f8e9cef0fc24b89065c22e576dc8821dd39a9d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,13 @@@
++@echo off
++
++REM -- Echo the git commit hash.  If git isn't available for some reason,
++REM -- output nothing instead.
++
++git rev-parse HEAD >NUL 2>NUL && (
++    git rev-parse HEAD
++) || (
++    echo none
++)
++
++REM -- Set ERRORLEVEL to 0 using this cryptic syntax.
++(call )
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..98215365ad239a551d584b0ec75a8dcbea59d11f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,54 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++// Recent 4.x MinGW and MinGW-w64 gcc compilers lack std::mutex and
++// std::lock_guard.  I have a 5.2.0 MinGW-w64 compiler packaged through MSYS2
++// that *is* new enough, but that's one compiler against several deficient
++// ones.  Wrap CRITICAL_SECTION instead.
++
++#ifndef WINPTY_SHARED_MUTEX_H
++#define WINPTY_SHARED_MUTEX_H
++
++#include <windows.h>
++
++class Mutex {
++    CRITICAL_SECTION m_mutex;
++public:
++    Mutex()         { InitializeCriticalSection(&m_mutex);  }
++    ~Mutex()        { DeleteCriticalSection(&m_mutex);      }
++    void lock()     { EnterCriticalSection(&m_mutex);       }
++    void unlock()   { LeaveCriticalSection(&m_mutex);       }
++
++    Mutex(const Mutex &other) = delete;
++    Mutex &operator=(const Mutex &other) = delete;
++};
++
++template <typename T>
++class LockGuard {
++    T &m_lock;
++public:
++    LockGuard(T &lock) : m_lock(lock)  { m_lock.lock();    }
++    ~LockGuard()                       { m_lock.unlock();  }
++
++    LockGuard(const LockGuard &other) = delete;
++    LockGuard &operator=(const LockGuard &other) = delete;
++};
++
++#endif // WINPTY_SHARED_MUTEX_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9713fa2b2dd2371c6983838d592a463c7c5b977e
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,63 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_OS_MODULE_H
++#define WINPTY_SHARED_OS_MODULE_H
++
++#include <windows.h>
++
++#include <string>
++
++#include "DebugClient.h"
++#include "WinptyAssert.h"
++#include "WinptyException.h"
++
++class OsModule {
++    HMODULE m_module;
++public:
++    enum class LoadErrorBehavior { Abort, Throw };
++    OsModule(const wchar_t *fileName,
++            LoadErrorBehavior behavior=LoadErrorBehavior::Abort) {
++        m_module = LoadLibraryW(fileName);
++        if (behavior == LoadErrorBehavior::Abort) {
++            ASSERT(m_module != NULL);
++        } else {
++            if (m_module == nullptr) {
++                const auto err = GetLastError();
++                throwWindowsError(
++                    (L"LoadLibraryW error: " + std::wstring(fileName)).c_str(),
++                    err);
++            }
++        }
++    }
++    ~OsModule() {
++        FreeLibrary(m_module);
++    }
++    HMODULE handle() const { return m_module; }
++    FARPROC proc(const char *funcName) {
++        FARPROC ret = GetProcAddress(m_module, funcName);
++        if (ret == NULL) {
++            trace("GetProcAddress: %s is missing", funcName);
++        }
++        return ret;
++    }
++};
++
++#endif // WINPTY_SHARED_OS_MODULE_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7b173536e6b7f1ce404792d768838f6e7ffa6c43
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,36 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "OwnedHandle.h"
++
++#include "DebugClient.h"
++#include "WinptyException.h"
++
++void OwnedHandle::dispose(bool nothrow) {
++    if (m_h != nullptr && m_h != INVALID_HANDLE_VALUE) {
++        if (!CloseHandle(m_h)) {
++            trace("CloseHandle(%p) failed", m_h);
++            if (!nothrow) {
++                throwWindowsError(L"CloseHandle failed");
++            }
++        }
++    }
++    m_h = nullptr;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..70a8d6163a97fbd3aae27c7d3aa8dcbd50d21a0b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,45 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_OWNED_HANDLE_H
++#define WINPTY_SHARED_OWNED_HANDLE_H
++
++#include <windows.h>
++
++class OwnedHandle {
++    HANDLE m_h;
++public:
++    OwnedHandle() : m_h(nullptr) {}
++    explicit OwnedHandle(HANDLE h) : m_h(h) {}
++    ~OwnedHandle() { dispose(true); }
++    void dispose(bool nothrow=false);
++    HANDLE get() const { return m_h; }
++    HANDLE release() { HANDLE ret = m_h; m_h = nullptr; return ret; }
++    OwnedHandle(const OwnedHandle &other) = delete;
++    OwnedHandle(OwnedHandle &&other) : m_h(other.release()) {}
++    OwnedHandle &operator=(const OwnedHandle &other) = delete;
++    OwnedHandle &operator=(OwnedHandle &&other) {
++        dispose();
++        m_h = other.release();
++        return *this;
++    }
++};
++
++#endif // WINPTY_SHARED_OWNED_HANDLE_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7d9b8f8b4af756e0a64fbd4ce34aa4cfddc43328
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,43 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_PRECOMPILED_HEADER_H
++#define WINPTY_PRECOMPILED_HEADER_H
++
++#include <windows.h>
++
++#include <stdarg.h>
++#include <stdint.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <wchar.h>
++
++#include <array>
++#include <limits>
++#include <memory>
++#include <new>
++#include <string>
++#include <tuple>
++#include <type_traits>
++#include <utility>
++#include <vector>
++
++#endif // WINPTY_PRECOMPILED_HEADER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..f3155bdd29e93a63148fe853a85d58e4c05c3904
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,227 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++// Efficient integer->string conversion and string concatenation.  The
++// hexadecimal conversion may optionally have leading zeros.  Other ways to
++// convert integers to strings in C++ suffer these drawbacks:
++//
++//  * std::stringstream: Inefficient, even more so than stdio.
++//
++//  * std::to_string: No hexadecimal output, tends to use heap allocation, not
++//    supported on Cygwin.
++//
++//  * stdio routines: Requires parsing a format string (inefficient).  The
++//    caller *must* know how large the content is for correctness.  The
++//    string-printf functions are extremely inconsistent on Windows.  In
++//    particular, 64-bit integers, wide strings, and return values are
++//    problem areas.
++//
++// StringBuilderTest.cc is a standalone program that tests this header.
++
++#ifndef WINPTY_STRING_BUILDER_H
++#define WINPTY_STRING_BUILDER_H
++
++#include <array>
++#include <string>
++#include <type_traits>
++
++#ifdef STRING_BUILDER_TESTING
++#include <assert.h>
++#define STRING_BUILDER_CHECK(cond) assert(cond)
++#else
++#define STRING_BUILDER_CHECK(cond)
++#endif // STRING_BUILDER_TESTING
++
++#include "WinptyAssert.h"
++
++template <typename C, size_t sz>
++struct ValueString {
++    std::array<C, sz> m_array;
++    size_t m_offset;
++    size_t m_size;
++
++    const C *c_str() const { return m_array.data() + m_offset; }
++    const C *data() const { return m_array.data() + m_offset; }
++    size_t size() const { return m_size; }
++    std::basic_string<C> str() const {
++        return std::basic_string<C>(data(), m_size);
++    }
++};
++
++#ifdef _MSC_VER
++// Disable an MSVC /SDL error that forbids unsigned negation.  Signed negation
++// invokes undefined behavior for INTxx_MIN, so unsigned negation is simpler to
++// reason about.  (We assume twos-complement in any case.)
++#define STRING_BUILDER_ALLOW_UNSIGNED_NEGATE(x) \
++    (                                           \
++        __pragma(warning(push))                 \
++        __pragma(warning(disable:4146))         \
++        (x)                                     \
++        __pragma(warning(pop))                  \
++    )
++#else
++#define STRING_BUILDER_ALLOW_UNSIGNED_NEGATE(x) (x)
++#endif
++
++// Formats an integer as decimal without leading zeros.
++template <typename C, typename I>
++ValueString<C, sizeof(I) * 3 + 1 + 1> gdecOfInt(const I value) {
++    typedef typename std::make_unsigned<I>::type U;
++    auto unsValue = static_cast<U>(value);
++    const bool isNegative = (value < 0);
++    if (isNegative) {
++        unsValue = STRING_BUILDER_ALLOW_UNSIGNED_NEGATE(-unsValue);
++    }
++    decltype(gdecOfInt<C, I>(value)) out;
++    auto &arr = out.m_array;
++    C *const endp = arr.data() + arr.size();
++    C *outp = endp;
++    *(--outp) = '\0';
++    STRING_BUILDER_CHECK(outp >= arr.data());
++    do {
++        const int digit = unsValue % 10;
++        unsValue /= 10;
++        *(--outp) = '0' + digit;
++        STRING_BUILDER_CHECK(outp >= arr.data());
++    } while (unsValue != 0);
++    if (isNegative) {
++        *(--outp) = '-';
++        STRING_BUILDER_CHECK(outp >= arr.data());
++    }
++    out.m_offset = outp - arr.data();
++    out.m_size = endp - outp - 1;
++    return out;
++}
++
++template <typename I> decltype(gdecOfInt<char, I>(0)) decOfInt(I i) {
++    return gdecOfInt<char>(i);
++}
++
++template <typename I> decltype(gdecOfInt<wchar_t, I>(0)) wdecOfInt(I i) {
++    return gdecOfInt<wchar_t>(i);
++}
++
++// Formats an integer as hexadecimal, with or without leading zeros.
++template <typename C, bool leadingZeros=false, typename I>
++ValueString<C, sizeof(I) * 2 + 1> ghexOfInt(const I value) {
++    typedef typename std::make_unsigned<I>::type U;
++    const auto unsValue = static_cast<U>(value);
++    static const C hex[16] = {'0','1','2','3','4','5','6','7',
++                              '8','9','a','b','c','d','e','f'};
++    decltype(ghexOfInt<C, leadingZeros, I>(value)) out;
++    auto &arr = out.m_array;
++    C *outp = arr.data();
++    int inIndex = 0;
++    int shift = sizeof(I) * 8 - 4;
++    const int len = sizeof(I) * 2;
++    if (!leadingZeros) {
++        for (; inIndex < len - 1; ++inIndex, shift -= 4) {
++            STRING_BUILDER_CHECK(shift >= 0 && shift < sizeof(unsValue) * 8);
++            const int digit = (unsValue >> shift) & 0xF;
++            if (digit != 0) {
++                break;
++            }
++        }
++    }
++    for (; inIndex < len; ++inIndex, shift -= 4) {
++        const int digit = (unsValue >> shift) & 0xF;
++        *(outp++) = hex[digit];
++        STRING_BUILDER_CHECK(outp <= arr.data() + arr.size());
++    }
++    *(outp++) = '\0';
++    STRING_BUILDER_CHECK(outp <= arr.data() + arr.size());
++    out.m_offset = 0;
++    out.m_size = outp - arr.data() - 1;
++    return out;
++}
++
++template <bool leadingZeros=false, typename I>
++decltype(ghexOfInt<char, leadingZeros, I>(0)) hexOfInt(I i) {
++    return ghexOfInt<char, leadingZeros, I>(i);
++}
++
++template <bool leadingZeros=false, typename I>
++decltype(ghexOfInt<wchar_t, leadingZeros, I>(0)) whexOfInt(I i) {
++    return ghexOfInt<wchar_t, leadingZeros, I>(i);
++}
++
++template <typename C>
++class GStringBuilder {
++public:
++    typedef std::basic_string<C> StringType;
++
++    GStringBuilder() {}
++    GStringBuilder(size_t capacity) {
++        m_out.reserve(capacity);
++    }
++
++    GStringBuilder &operator<<(C ch) { m_out.push_back(ch); return *this; }
++    GStringBuilder &operator<<(const C *str) { m_out.append(str); return *this; }
++    GStringBuilder &operator<<(const StringType &str) { m_out.append(str); return *this; }
++
++    template <size_t sz>
++    GStringBuilder &operator<<(const ValueString<C, sz> &str) {
++        m_out.append(str.data(), str.size());
++        return *this;
++    }
++
++private:
++    // Forbid output of char/wchar_t for GStringBuilder if the type doesn't
++    // exactly match the builder element type.  The code still allows
++    // signed char and unsigned char, but I'm a little worried about what
++    // happens if a user tries to output int8_t or uint8_t.
++    template <typename P>
++    typename std::enable_if<
++        (std::is_same<P, char>::value || std::is_same<P, wchar_t>::value) &&
++        !std::is_same<C, P>::value, GStringBuilder&>::type
++    operator<<(P ch) {
++        ASSERT(false && "Method was not supposed to be reachable.");
++        return *this;
++    }
++
++public:
++    GStringBuilder &operator<<(short i)              { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(unsigned short i)     { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(int i)                { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(unsigned int i)       { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(long i)               { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(unsigned long i)      { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(long long i)          { return *this << gdecOfInt<C>(i); }
++    GStringBuilder &operator<<(unsigned long long i) { return *this << gdecOfInt<C>(i); }
++
++    GStringBuilder &operator<<(const void *p) {
++        m_out.push_back(static_cast<C>('0'));
++        m_out.push_back(static_cast<C>('x'));
++        *this << ghexOfInt<C>(reinterpret_cast<uintptr_t>(p));
++        return *this;
++    }
++
++    StringType str() { return m_out; }
++    StringType str_moved() { return std::move(m_out); }
++    const C *c_str() const { return m_out.c_str(); }
++
++private:
++    StringType m_out;
++};
++
++typedef GStringBuilder<char> StringBuilder;
++typedef GStringBuilder<wchar_t> WStringBuilder;
++
++#endif // WINPTY_STRING_BUILDER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e6c2d3138c88c626b52b7b2e0012559e95a1dc83
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,114 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#define STRING_BUILDER_TESTING
++
++#include "StringBuilder.h"
++
++#include <stdio.h>
++#include <string.h>
++
++#include <iomanip>
++#include <sstream>
++
++void display(const std::string &str) { fprintf(stderr, "%s", str.c_str()); }
++void display(const std::wstring &str) { fprintf(stderr, "%ls", str.c_str()); }
++
++#define CHECK_EQ(x, y) \
++    do {                                                    \
++        const auto xval = (x);                              \
++        const auto yval = (y);                              \
++        if (xval != yval) {                                 \
++            fprintf(stderr, "error: %s:%d: %s != %s: ",     \
++                __FILE__, __LINE__, #x, #y);                \
++            display(xval);                                  \
++            fprintf(stderr, " != ");                        \
++            display(yval);                                  \
++            fprintf(stderr, "\n");                          \
++        }                                                   \
++    } while(0)
++
++template <typename C, typename I>
++std::basic_string<C> decOfIntSS(const I value) {
++    // std::to_string and std::to_wstring are missing in Cygwin as of this
++    // writing (early 2016).
++    std::basic_stringstream<C> ss;
++    ss << +value; // We must promote char to print it as an integer.
++    return ss.str();
++}
++
++
++template <typename C, bool leadingZeros=false, typename I>
++std::basic_string<C> hexOfIntSS(const I value) {
++    typedef typename std::make_unsigned<I>::type U;
++    const unsigned long long u64Value = value & static_cast<U>(~0);
++    std::basic_stringstream<C> ss;
++    if (leadingZeros) {
++        ss << std::setfill(static_cast<C>('0')) << std::setw(sizeof(I) * 2);
++    }
++    ss << std::hex << u64Value;
++    return ss.str();
++}
++
++template <typename I>
++void testValue(I value) {
++    CHECK_EQ(decOfInt(value).str(), (decOfIntSS<char>(value)));
++    CHECK_EQ(wdecOfInt(value).str(), (decOfIntSS<wchar_t>(value)));
++    CHECK_EQ((hexOfInt<false>(value).str()), (hexOfIntSS<char, false>(value)));
++    CHECK_EQ((hexOfInt<true>(value).str()), (hexOfIntSS<char, true>(value)));
++    CHECK_EQ((whexOfInt<false>(value).str()), (hexOfIntSS<wchar_t, false>(value)));
++    CHECK_EQ((whexOfInt<true>(value).str()), (hexOfIntSS<wchar_t, true>(value)));
++}
++
++template <typename I>
++void testType() {
++    typedef typename std::make_unsigned<I>::type U;
++    const U quarter = static_cast<U>(1) << (sizeof(U) * 8 - 2);
++    for (unsigned quarterIndex = 0; quarterIndex < 4; ++quarterIndex) {
++        for (int offset = -18; offset <= 18; ++offset) {
++            const I value = quarter * quarterIndex + static_cast<U>(offset);
++            testValue(value);
++        }
++    }
++    testValue(static_cast<I>(42));
++    testValue(static_cast<I>(123456));
++    testValue(static_cast<I>(0xdeadfacecafebeefull));
++}
++
++int main() {
++    testType<char>();
++
++    testType<signed char>();
++    testType<signed short>();
++    testType<signed int>();
++    testType<signed long>();
++    testType<signed long long>();
++
++    testType<unsigned char>();
++    testType<unsigned short>();
++    testType<unsigned int>();
++    testType<unsigned long>();
++    testType<unsigned long long>();
++
++    StringBuilder() << static_cast<const void*>("TEST");
++    WStringBuilder() << static_cast<const void*>("TEST");
++
++    fprintf(stderr, "All tests completed!\n");
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3a85a3ec9418afb4592fabcb1859d562fe3b73c6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,55 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "StringUtil.h"
++
++#include <windows.h>
++
++#include "WinptyAssert.h"
++
++// Workaround.  MinGW (from mingw.org) does not have wcsnlen.  MinGW-w64 *does*
++// have wcsnlen, but use this function for consistency.
++size_t winpty_wcsnlen(const wchar_t *s, size_t maxlen) {
++    ASSERT(s != NULL);
++    for (size_t i = 0; i < maxlen; ++i) {
++        if (s[i] == L'\0') {
++            return i;
++        }
++    }
++    return maxlen;
++}
++
++std::string utf8FromWide(const std::wstring &input) {
++    int mblen = WideCharToMultiByte(
++        CP_UTF8, 0,
++        input.data(), input.size(),
++        NULL, 0, NULL, NULL);
++    if (mblen <= 0) {
++        return std::string();
++    }
++    std::vector<char> tmp(mblen);
++    int mblen2 = WideCharToMultiByte(
++        CP_UTF8, 0,
++        input.data(), input.size(),
++        tmp.data(), tmp.size(),
++        NULL, NULL);
++    ASSERT(mblen2 == mblen);
++    return std::string(tmp.data(), tmp.size());
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e4bf3c91212816a12537e1b52d92bf3ad1c8945d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,80 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_STRING_UTIL_H
++#define WINPTY_SHARED_STRING_UTIL_H
++
++#include <stdlib.h>
++#include <string.h>
++#include <wchar.h>
++
++#include <algorithm>
++#include <string>
++#include <vector>
++
++#include "WinptyAssert.h"
++
++size_t winpty_wcsnlen(const wchar_t *s, size_t maxlen);
++std::string utf8FromWide(const std::wstring &input);
++
++// Return a vector containing each character in the string.
++template <typename T>
++std::vector<T> vectorFromString(const std::basic_string<T> &str) {
++    return std::vector<T>(str.begin(), str.end());
++}
++
++// Return a vector containing each character in the string, followed by a
++// NUL terminator.
++template <typename T>
++std::vector<T> vectorWithNulFromString(const std::basic_string<T> &str) {
++    std::vector<T> ret;
++    ret.reserve(str.size() + 1);
++    ret.insert(ret.begin(), str.begin(), str.end());
++    ret.push_back('\0');
++    return ret;
++}
++
++// A safer(?) version of wcsncpy that is accepted by MSVC's /SDL mode.
++template <size_t N>
++wchar_t *winpty_wcsncpy(wchar_t (&d)[N], const wchar_t *s) {
++    ASSERT(s != nullptr);
++    size_t i = 0;
++    for (; i < N; ++i) {
++        if (s[i] == L'\0') {
++            break;
++        }
++        d[i] = s[i];
++    }
++    for (; i < N; ++i) {
++        d[i] = L'\0';
++    }
++    return d;
++}
++
++// Like wcsncpy, but ensure that the destination buffer is NUL-terminated.
++template <size_t N>
++wchar_t *winpty_wcsncpy_nul(wchar_t (&d)[N], const wchar_t *s) {
++    static_assert(N > 0, "array cannot be 0-size");
++    winpty_wcsncpy(d, s);
++    d[N - 1] = L'\0';
++    return d;
++}
++
++#endif // WINPTY_SHARED_STRING_UTIL_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..716a027fcbdf9deb1d3f0f5e416b40b0b6d7239d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,63 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++// Convenience header library for using the high-resolution performance counter
++// to measure how long some process takes.
++
++#ifndef TIME_MEASUREMENT_H
++#define TIME_MEASUREMENT_H
++
++#include <windows.h>
++#include <assert.h>
++#include <stdint.h>
++
++class TimeMeasurement {
++public:
++    TimeMeasurement() {
++        static double freq = static_cast<double>(getFrequency());
++        m_freq = freq;
++        m_start = value();
++    }
++
++    double elapsed() {
++        uint64_t elapsedTicks = value() - m_start;
++        return static_cast<double>(elapsedTicks) / m_freq;
++    }
++
++private:
++    uint64_t getFrequency() {
++        LARGE_INTEGER freq;
++        BOOL success = QueryPerformanceFrequency(&freq);
++        assert(success && "QueryPerformanceFrequency failed");
++        return freq.QuadPart;
++    }
++
++    uint64_t value() {
++        LARGE_INTEGER ret;
++        BOOL success = QueryPerformanceCounter(&ret);
++        assert(success && "QueryPerformanceCounter failed");
++        return ret.QuadPart;
++    }
++
++    uint64_t m_start;
++    double m_freq;
++};
++
++#endif // TIME_MEASUREMENT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..39dfa62ec9fb5e24cdd8e5da9118e69045016f2b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,45 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef UNIX_CTRL_CHARS_H
++#define UNIX_CTRL_CHARS_H
++
++inline char decodeUnixCtrlChar(char ch) {
++    const char ctrlKeys[] = {
++        /* 0x00 */ '@', /* 0x01 */ 'A', /* 0x02 */ 'B', /* 0x03 */ 'C',
++        /* 0x04 */ 'D', /* 0x05 */ 'E', /* 0x06 */ 'F', /* 0x07 */ 'G',
++        /* 0x08 */ 'H', /* 0x09 */ 'I', /* 0x0A */ 'J', /* 0x0B */ 'K',
++        /* 0x0C */ 'L', /* 0x0D */ 'M', /* 0x0E */ 'N', /* 0x0F */ 'O',
++        /* 0x10 */ 'P', /* 0x11 */ 'Q', /* 0x12 */ 'R', /* 0x13 */ 'S',
++        /* 0x14 */ 'T', /* 0x15 */ 'U', /* 0x16 */ 'V', /* 0x17 */ 'W',
++        /* 0x18 */ 'X', /* 0x19 */ 'Y', /* 0x1A */ 'Z', /* 0x1B */ '[',
++        /* 0x1C */ '\\', /* 0x1D */ ']', /* 0x1E */ '^', /* 0x1F */ '_',
++    };
++    unsigned char uch = ch;
++    if (uch < 32) {
++        return ctrlKeys[uch];
++    } else if (uch == 127) {
++        return '?';
++    } else {
++        return '\0';
++    }
++}
++
++#endif // UNIX_CTRL_CHARS_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ea2a7d64ed59f6570e7e467da5bcf8fae04ba2fb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,20 @@@
++@echo off
++
++rem -- Echo the git commit hash.  If git isn't available for some reason,
++rem -- output nothing instead.
++
++mkdir ..\gen 2>nul
++
++set /p VERSION=<..\..\VERSION.txt
++set COMMIT=%1
++
++echo // AUTO-GENERATED BY %0 %*>..\gen\GenVersion.h
++echo const char GenVersion_Version[] = "%VERSION%";>>..\gen\GenVersion.h
++echo const char GenVersion_Commit[] = "%COMMIT%";>>..\gen\GenVersion.h
++
++rem -- The winpty.gyp file expects the script to output the include directory,
++rem -- relative to src.
++echo gen
++
++rem -- Set ERRORLEVEL to 0 using this cryptic syntax.
++(call )
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..711a8637c8cb82e74179d9505e0f87cadeecec2f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,460 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "WindowsSecurity.h"
++
++#include <array>
++
++#include "DebugClient.h"
++#include "OsModule.h"
++#include "OwnedHandle.h"
++#include "StringBuilder.h"
++#include "WindowsVersion.h"
++#include "WinptyAssert.h"
++#include "WinptyException.h"
++
++namespace {
++
++struct LocalFreer {
++    void operator()(void *ptr) {
++        if (ptr != nullptr) {
++            LocalFree(reinterpret_cast<HLOCAL>(ptr));
++        }
++    }
++};
++
++typedef std::unique_ptr<void, LocalFreer> PointerLocal;
++
++template <typename T>
++SecurityItem<T> localItem(typename T::type v) {
++    typedef typename T::type P;
++    struct Impl : SecurityItem<T>::Impl {
++        P m_v;
++        Impl(P v) : m_v(v) {}
++        virtual ~Impl() {
++            LocalFree(reinterpret_cast<HLOCAL>(m_v));
++        }
++    };
++    return SecurityItem<T>(v, std::unique_ptr<Impl>(new Impl { v }));
++}
++
++Sid allocatedSid(PSID v) {
++    struct Impl : Sid::Impl {
++        PSID m_v;
++        Impl(PSID v) : m_v(v) {}
++        virtual ~Impl() {
++            if (m_v != nullptr) {
++                FreeSid(m_v);
++            }
++        }
++    };
++    return Sid(v, std::unique_ptr<Impl>(new Impl { v }));
++}
++
++} // anonymous namespace
++
++// Returns a handle to the thread's effective security token.  If the thread
++// is impersonating another user, its token is returned, and otherwise, the
++// process' security token is opened.  The handle is opened with TOKEN_QUERY.
++static OwnedHandle openSecurityTokenForQuery() {
++    HANDLE token = nullptr;
++    // It is unclear to me whether OpenAsSelf matters for winpty, or what the
++    // most appropriate value is.
++    if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY,
++                         /*OpenAsSelf=*/FALSE, &token)) {
++        if (GetLastError() != ERROR_NO_TOKEN) {
++            throwWindowsError(L"OpenThreadToken failed");
++        }
++        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
++            throwWindowsError(L"OpenProcessToken failed");
++        }
++    }
++    ASSERT(token != nullptr &&
++        "OpenThreadToken/OpenProcessToken token is NULL");
++    return OwnedHandle(token);
++}
++
++// Returns the TokenOwner of the thread's effective security token.
++Sid getOwnerSid() {
++    struct Impl : Sid::Impl {
++        std::unique_ptr<char[]> buffer;
++    };
++
++    OwnedHandle token = openSecurityTokenForQuery();
++    DWORD actual = 0;
++    BOOL success;
++    success = GetTokenInformation(token.get(), TokenOwner,
++        nullptr, 0, &actual);
++    if (success) {
++        throwWinptyException(L"getOwnerSid: GetTokenInformation: "
++            L"expected ERROR_INSUFFICIENT_BUFFER");
++    } else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
++        throwWindowsError(L"getOwnerSid: GetTokenInformation: "
++            L"expected ERROR_INSUFFICIENT_BUFFER");
++    }
++    std::unique_ptr<Impl> impl(new Impl);
++    impl->buffer = std::unique_ptr<char[]>(new char[actual]);
++    success = GetTokenInformation(token.get(), TokenOwner,
++                                  impl->buffer.get(), actual, &actual);
++    if (!success) {
++        throwWindowsError(L"getOwnerSid: GetTokenInformation");
++    }
++    TOKEN_OWNER tmp;
++    ASSERT(actual >= sizeof(tmp));
++    std::copy(
++        impl->buffer.get(),
++        impl->buffer.get() + sizeof(tmp),
++        reinterpret_cast<char*>(&tmp));
++    return Sid(tmp.Owner, std::move(impl));
++}
++
++Sid wellKnownSid(
++        const wchar_t *debuggingName,
++        SID_IDENTIFIER_AUTHORITY authority,
++        BYTE authorityCount,
++        DWORD subAuthority0/*=0*/,
++        DWORD subAuthority1/*=0*/) {
++    PSID psid = nullptr;
++    if (!AllocateAndInitializeSid(&authority, authorityCount,
++            subAuthority0,
++            subAuthority1,
++            0, 0, 0, 0, 0, 0,
++            &psid)) {
++        const auto err = GetLastError();
++        const auto msg =
++            std::wstring(L"wellKnownSid: error getting ") +
++            debuggingName + L" SID";
++        throwWindowsError(msg.c_str(), err);
++    }
++    return allocatedSid(psid);
++}
++
++Sid builtinAdminsSid() {
++    // S-1-5-32-544
++    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };
++    return wellKnownSid(L"BUILTIN\\Administrators group",
++            authority, 2,
++            SECURITY_BUILTIN_DOMAIN_RID,    // 32
++            DOMAIN_ALIAS_RID_ADMINS);       // 544
++}
++
++Sid localSystemSid() {
++    // S-1-5-18
++    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };
++    return wellKnownSid(L"LocalSystem account",
++            authority, 1,
++            SECURITY_LOCAL_SYSTEM_RID);     // 18
++}
++
++Sid everyoneSid() {
++    // S-1-1-0
++    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_WORLD_SID_AUTHORITY };
++    return wellKnownSid(L"Everyone account",
++            authority, 1,
++            SECURITY_WORLD_RID);            // 0
++}
++
++static SecurityDescriptor finishSecurityDescriptor(
++        size_t daclEntryCount,
++        EXPLICIT_ACCESSW *daclEntries,
++        Acl &outAcl) {
++    {
++        PACL aclRaw = nullptr;
++        DWORD aclError =
++            SetEntriesInAclW(daclEntryCount,
++                             daclEntries,
++                             nullptr, &aclRaw);
++        if (aclError != ERROR_SUCCESS) {
++            WStringBuilder sb(64);
++            sb << L"finishSecurityDescriptor: "
++               << L"SetEntriesInAcl failed: " << aclError;
++            throwWinptyException(sb.c_str());
++        }
++        outAcl = localItem<AclTag>(aclRaw);
++    }
++
++    const PSECURITY_DESCRIPTOR sdRaw =
++        reinterpret_cast<PSECURITY_DESCRIPTOR>(
++            LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH));
++    if (sdRaw == nullptr) {
++        throwWinptyException(L"finishSecurityDescriptor: LocalAlloc failed");
++    }
++    SecurityDescriptor sd = localItem<SecurityDescriptorTag>(sdRaw);
++    if (!InitializeSecurityDescriptor(sdRaw, SECURITY_DESCRIPTOR_REVISION)) {
++        throwWindowsError(
++            L"finishSecurityDescriptor: InitializeSecurityDescriptor");
++    }
++    if (!SetSecurityDescriptorDacl(sdRaw, TRUE, outAcl.get(), FALSE)) {
++        throwWindowsError(
++            L"finishSecurityDescriptor: SetSecurityDescriptorDacl");
++    }
++
++    return std::move(sd);
++}
++
++// Create a security descriptor that grants full control to the local system
++// account, built-in administrators, and the owner.
++SecurityDescriptor
++createPipeSecurityDescriptorOwnerFullControl() {
++
++    struct Impl : SecurityDescriptor::Impl {
++        Sid localSystem;
++        Sid builtinAdmins;
++        Sid owner;
++        std::array<EXPLICIT_ACCESSW, 3> daclEntries = {};
++        Acl dacl;
++        SecurityDescriptor value;
++    };
++
++    std::unique_ptr<Impl> impl(new Impl);
++    impl->localSystem = localSystemSid();
++    impl->builtinAdmins = builtinAdminsSid();
++    impl->owner = getOwnerSid();
++
++    for (auto &ea : impl->daclEntries) {
++        ea.grfAccessPermissions = GENERIC_ALL;
++        ea.grfAccessMode = SET_ACCESS;
++        ea.grfInheritance = NO_INHERITANCE;
++        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
++    }
++    impl->daclEntries[0].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->localSystem.get());
++    impl->daclEntries[1].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->builtinAdmins.get());
++    impl->daclEntries[2].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->owner.get());
++
++    impl->value = finishSecurityDescriptor(
++        impl->daclEntries.size(),
++        impl->daclEntries.data(),
++        impl->dacl);
++
++    const auto retValue = impl->value.get();
++    return SecurityDescriptor(retValue, std::move(impl));
++}
++
++SecurityDescriptor
++createPipeSecurityDescriptorOwnerFullControlEveryoneWrite() {
++
++    struct Impl : SecurityDescriptor::Impl {
++        Sid localSystem;
++        Sid builtinAdmins;
++        Sid owner;
++        Sid everyone;
++        std::array<EXPLICIT_ACCESSW, 4> daclEntries = {};
++        Acl dacl;
++        SecurityDescriptor value;
++    };
++
++    std::unique_ptr<Impl> impl(new Impl);
++    impl->localSystem = localSystemSid();
++    impl->builtinAdmins = builtinAdminsSid();
++    impl->owner = getOwnerSid();
++    impl->everyone = everyoneSid();
++
++    for (auto &ea : impl->daclEntries) {
++        ea.grfAccessPermissions = GENERIC_ALL;
++        ea.grfAccessMode = SET_ACCESS;
++        ea.grfInheritance = NO_INHERITANCE;
++        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
++    }
++    impl->daclEntries[0].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->localSystem.get());
++    impl->daclEntries[1].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->builtinAdmins.get());
++    impl->daclEntries[2].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->owner.get());
++    impl->daclEntries[3].Trustee.ptstrName =
++        reinterpret_cast<LPWSTR>(impl->everyone.get());
++    // Avoid using FILE_GENERIC_WRITE because it includes FILE_APPEND_DATA,
++    // which is equal to FILE_CREATE_PIPE_INSTANCE.  Instead, include all the
++    // flags that comprise FILE_GENERIC_WRITE, except for the one.
++    impl->daclEntries[3].grfAccessPermissions =
++        FILE_GENERIC_READ |
++        FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | FILE_WRITE_EA |
++        STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
++
++    impl->value = finishSecurityDescriptor(
++        impl->daclEntries.size(),
++        impl->daclEntries.data(),
++        impl->dacl);
++
++    const auto retValue = impl->value.get();
++    return SecurityDescriptor(retValue, std::move(impl));
++}
++
++SecurityDescriptor getObjectSecurityDescriptor(HANDLE handle) {
++    PACL dacl = nullptr;
++    PSECURITY_DESCRIPTOR sd = nullptr;
++    const DWORD errCode = GetSecurityInfo(handle, SE_KERNEL_OBJECT,
++        OWNER_SECURITY_INFORMATION |
++            GROUP_SECURITY_INFORMATION |
++            DACL_SECURITY_INFORMATION,
++        nullptr, nullptr, &dacl, nullptr, &sd);
++    if (errCode != ERROR_SUCCESS) {
++        throwWindowsError(L"GetSecurityInfo failed");
++    }
++    return localItem<SecurityDescriptorTag>(sd);
++}
++
++// The (SID/SD)<->string conversion APIs are useful for testing/debugging, so
++// create convenient accessor functions for them.  They're too slow for
++// ordinary use.  The APIs exist in XP and up, but the MinGW headers only
++// declare the SID<->string APIs, not the SD APIs.  MinGW also gets the
++// prototype wrong for ConvertStringSidToSidW (LPWSTR instead of LPCWSTR) and
++// requires WINVER to be defined.  MSVC and MinGW-w64 get everything right, but
++// for consistency, use LoadLibrary/GetProcAddress for all four APIs.
++
++typedef BOOL WINAPI ConvertStringSidToSidW_t(
++    LPCWSTR StringSid,
++    PSID *Sid);
++
++typedef BOOL WINAPI ConvertSidToStringSidW_t(
++    PSID Sid,
++    LPWSTR *StringSid);
++
++typedef BOOL WINAPI ConvertStringSecurityDescriptorToSecurityDescriptorW_t(
++    LPCWSTR StringSecurityDescriptor,
++    DWORD StringSDRevision,
++    PSECURITY_DESCRIPTOR *SecurityDescriptor,
++    PULONG SecurityDescriptorSize);
++
++typedef BOOL WINAPI ConvertSecurityDescriptorToStringSecurityDescriptorW_t(
++    PSECURITY_DESCRIPTOR SecurityDescriptor,
++    DWORD RequestedStringSDRevision,
++    SECURITY_INFORMATION SecurityInformation,
++    LPWSTR *StringSecurityDescriptor,
++    PULONG StringSecurityDescriptorLen);
++
++#define GET_MODULE_PROC(mod, funcName)                                      \
++    const auto p##funcName =                                                \
++        reinterpret_cast<funcName##_t*>(                                    \
++            mod.proc(#funcName));                                           \
++    if (p##funcName == nullptr) {                                           \
++        throwWinptyException(                                               \
++            L"" L ## #funcName L" API is missing from ADVAPI32.DLL");     \
++    }
++
++const DWORD kSDDL_REVISION_1 = 1;
++
++std::wstring sidToString(PSID sid) {
++    OsModule advapi32(L"advapi32.dll");
++    GET_MODULE_PROC(advapi32, ConvertSidToStringSidW);
++    wchar_t *sidString = NULL;
++    BOOL success = pConvertSidToStringSidW(sid, &sidString);
++    if (!success) {
++        throwWindowsError(L"ConvertSidToStringSidW failed");
++    }
++    PointerLocal freer(sidString);
++    return std::wstring(sidString);
++}
++
++Sid stringToSid(const std::wstring &str) {
++    // Cast the string from const wchar_t* to LPWSTR because the function is
++    // incorrectly prototyped in the MinGW sddl.h header.  The API does not
++    // modify the string -- it is correctly prototyped as taking LPCWSTR in
++    // MinGW-w64, MSVC, and MSDN.
++    OsModule advapi32(L"advapi32.dll");
++    GET_MODULE_PROC(advapi32, ConvertStringSidToSidW);
++    PSID psid = nullptr;
++    BOOL success = pConvertStringSidToSidW(const_cast<LPWSTR>(str.c_str()),
++                                           &psid);
++    if (!success) {
++        const auto err = GetLastError();
++        throwWindowsError(
++            (std::wstring(L"ConvertStringSidToSidW failed on \"") +
++                str + L'"').c_str(),
++            err);
++    }
++    return localItem<SidTag>(psid);
++}
++
++SecurityDescriptor stringToSd(const std::wstring &str) {
++    OsModule advapi32(L"advapi32.dll");
++    GET_MODULE_PROC(advapi32, ConvertStringSecurityDescriptorToSecurityDescriptorW);
++    PSECURITY_DESCRIPTOR desc = nullptr;
++    if (!pConvertStringSecurityDescriptorToSecurityDescriptorW(
++            str.c_str(), kSDDL_REVISION_1, &desc, nullptr)) {
++        const auto err = GetLastError();
++        throwWindowsError(
++            (std::wstring(L"ConvertStringSecurityDescriptorToSecurityDescriptorW failed on \"") +
++                str + L'"').c_str(),
++            err);
++    }
++    return localItem<SecurityDescriptorTag>(desc);
++}
++
++std::wstring sdToString(PSECURITY_DESCRIPTOR sd) {
++    OsModule advapi32(L"advapi32.dll");
++    GET_MODULE_PROC(advapi32, ConvertSecurityDescriptorToStringSecurityDescriptorW);
++    wchar_t *sdString = nullptr;
++    if (!pConvertSecurityDescriptorToStringSecurityDescriptorW(
++            sd,
++            kSDDL_REVISION_1,
++            OWNER_SECURITY_INFORMATION |
++                GROUP_SECURITY_INFORMATION |
++                DACL_SECURITY_INFORMATION,
++            &sdString,
++            nullptr)) {
++        throwWindowsError(
++            L"ConvertSecurityDescriptorToStringSecurityDescriptor failed");
++    }
++    PointerLocal freer(sdString);
++    return std::wstring(sdString);
++}
++
++// Vista added a useful flag to CreateNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
++// that rejects remote connections.  Return this flag on Vista, or return 0
++// otherwise.
++DWORD rejectRemoteClientsPipeFlag() {
++    if (isAtLeastWindowsVista()) {
++        // MinGW lacks this flag; MinGW-w64 has it.
++        const DWORD kPIPE_REJECT_REMOTE_CLIENTS = 8;
++        return kPIPE_REJECT_REMOTE_CLIENTS;
++    } else {
++        trace("Omitting PIPE_REJECT_REMOTE_CLIENTS on pre-Vista OS");
++        return 0;
++    }
++}
++
++typedef BOOL WINAPI GetNamedPipeClientProcessId_t(
++    HANDLE Pipe,
++    PULONG ClientProcessId);
++
++std::tuple<GetNamedPipeClientProcessId_Result, DWORD, DWORD>
++getNamedPipeClientProcessId(HANDLE serverPipe) {
++    OsModule kernel32(L"kernel32.dll");
++    const auto pGetNamedPipeClientProcessId =
++        reinterpret_cast<GetNamedPipeClientProcessId_t*>(
++            kernel32.proc("GetNamedPipeClientProcessId"));
++    if (pGetNamedPipeClientProcessId == nullptr) {
++        return std::make_tuple(
++            GetNamedPipeClientProcessId_Result::UnsupportedOs, 0, 0);
++    }
++    ULONG pid = 0;
++    if (!pGetNamedPipeClientProcessId(serverPipe, &pid)) {
++        return std::make_tuple(
++            GetNamedPipeClientProcessId_Result::Failure, 0, GetLastError());
++    }
++    return std::make_tuple(
++        GetNamedPipeClientProcessId_Result::Success,
++        static_cast<DWORD>(pid),
++        0);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..5f9d53aff6df5852b14c6954625c77f126f663bd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,104 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_WINDOWS_SECURITY_H
++#define WINPTY_WINDOWS_SECURITY_H
++
++#include <windows.h>
++#include <aclapi.h>
++
++#include <memory>
++#include <string>
++#include <tuple>
++#include <utility>
++
++// PSID and PSECURITY_DESCRIPTOR are both pointers to void, but we want
++// Sid and SecurityDescriptor to be different types.
++struct SidTag                   {   typedef PSID type;                  };
++struct AclTag                   {   typedef PACL type;                  };
++struct SecurityDescriptorTag    {   typedef PSECURITY_DESCRIPTOR type;  };
++
++template <typename T>
++class SecurityItem {
++public:
++    struct Impl {
++        virtual ~Impl() {}
++    };
++
++private:
++    typedef typename T::type P;
++    P m_v;
++    std::unique_ptr<Impl> m_pimpl;
++
++public:
++    P get() const { return m_v; }
++    operator bool() const { return m_v != nullptr; }
++
++    SecurityItem() : m_v(nullptr) {}
++    SecurityItem(P v, std::unique_ptr<Impl> &&pimpl) :
++            m_v(v), m_pimpl(std::move(pimpl)) {}
++    SecurityItem(SecurityItem &&other) :
++            m_v(other.m_v), m_pimpl(std::move(other.m_pimpl)) {
++        other.m_v = nullptr;
++    }
++    SecurityItem &operator=(SecurityItem &&other) {
++        m_v = other.m_v;
++        other.m_v = nullptr;
++        m_pimpl = std::move(other.m_pimpl);
++        return *this;
++    }
++};
++
++typedef SecurityItem<SidTag> Sid;
++typedef SecurityItem<AclTag> Acl;
++typedef SecurityItem<SecurityDescriptorTag> SecurityDescriptor;
++
++Sid getOwnerSid();
++Sid wellKnownSid(
++    const wchar_t *debuggingName,
++    SID_IDENTIFIER_AUTHORITY authority,
++    BYTE authorityCount,
++    DWORD subAuthority0=0,
++    DWORD subAuthority1=0);
++Sid builtinAdminsSid();
++Sid localSystemSid();
++Sid everyoneSid();
++
++SecurityDescriptor createPipeSecurityDescriptorOwnerFullControl();
++SecurityDescriptor createPipeSecurityDescriptorOwnerFullControlEveryoneWrite();
++SecurityDescriptor getObjectSecurityDescriptor(HANDLE handle);
++
++std::wstring sidToString(PSID sid);
++Sid stringToSid(const std::wstring &str);
++SecurityDescriptor stringToSd(const std::wstring &str);
++std::wstring sdToString(PSECURITY_DESCRIPTOR sd);
++
++DWORD rejectRemoteClientsPipeFlag();
++
++enum class GetNamedPipeClientProcessId_Result {
++    Success,
++    Failure,
++    UnsupportedOs,
++};
++
++std::tuple<GetNamedPipeClientProcessId_Result, DWORD, DWORD>
++getNamedPipeClientProcessId(HANDLE serverPipe);
++
++#endif // WINPTY_WINDOWS_SECURITY_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d89b00d83822fb9605215a6b0549abf4186c75cf
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,252 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "WindowsVersion.h"
++
++#include <windows.h>
++#include <stdint.h>
++
++#include <memory>
++#include <string>
++#include <tuple>
++
++#include "DebugClient.h"
++#include "OsModule.h"
++#include "StringBuilder.h"
++#include "StringUtil.h"
++#include "WinptyAssert.h"
++#include "WinptyException.h"
++
++namespace {
++
++typedef std::tuple<DWORD, DWORD> Version;
++
++// This function can only return a version up to 6.2 unless the executable is
++// manifested for a newer version of Windows.  See the MSDN documentation for
++// GetVersionEx.
++OSVERSIONINFOEX getWindowsVersionInfo() {
++    // Allow use of deprecated functions (i.e. GetVersionEx).  We need to use
++    // GetVersionEx for the old MinGW toolchain and with MSVC when it targets XP.
++    // Having two code paths makes code harder to test, and it's not obvious how
++    // to detect the presence of a new enough SDK.  (Including ntverp.h and
++    // examining VER_PRODUCTBUILD apparently works, but even then, MinGW-w64 and
++    // MSVC seem to use different version numbers.)
++#ifdef _MSC_VER
++#pragma warning(push)
++#pragma warning(disable:4996)
++#endif
++    OSVERSIONINFOEX info = {};
++    info.dwOSVersionInfoSize = sizeof(info);
++    const auto success = GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&info));
++    ASSERT(success && "GetVersionEx failed");
++    return info;
++#ifdef _MSC_VER
++#pragma warning(pop)
++#endif
++}
++
++Version getWindowsVersion() {
++    const auto info = getWindowsVersionInfo();
++    return Version(info.dwMajorVersion, info.dwMinorVersion);
++}
++
++struct ModuleNotFound : WinptyException {
++    virtual const wchar_t *what() const WINPTY_NOEXCEPT override {
++        return L"ModuleNotFound";
++    }
++};
++
++// Throws WinptyException on error.
++std::wstring getSystemDirectory() {
++    wchar_t systemDirectory[MAX_PATH];
++    const UINT size = GetSystemDirectoryW(systemDirectory, MAX_PATH);
++    if (size == 0) {
++        throwWindowsError(L"GetSystemDirectory failed");
++    } else if (size >= MAX_PATH) {
++        throwWinptyException(
++            L"GetSystemDirectory: path is longer than MAX_PATH");
++    }
++    return systemDirectory;
++}
++
++#define GET_VERSION_DLL_API(name) \
++    const auto p ## name =                                  \
++        reinterpret_cast<decltype(name)*>(                  \
++            versionDll.proc(#name));                        \
++    if (p ## name == nullptr) {                             \
++        throwWinptyException(L ## #name L" is missing");    \
++    }
++
++// Throws WinptyException on error.
++VS_FIXEDFILEINFO getFixedFileInfo(const std::wstring &path) {
++    // version.dll is not a conventional KnownDll, so if we link to it, there's
++    // a danger of accidentally loading a malicious DLL.  In a more typical
++    // application, perhaps we'd guard against this security issue by
++    // controlling which directories this code runs in (e.g. *not* the
++    // "Downloads" directory), but that's harder for the winpty library.
++    OsModule versionDll(
++        (getSystemDirectory() + L"\\version.dll").c_str(),
++        OsModule::LoadErrorBehavior::Throw);
++    GET_VERSION_DLL_API(GetFileVersionInfoSizeW);
++    GET_VERSION_DLL_API(GetFileVersionInfoW);
++    GET_VERSION_DLL_API(VerQueryValueW);
++    DWORD size = pGetFileVersionInfoSizeW(path.c_str(), nullptr);
++    if (!size) {
++        // I see ERROR_FILE_NOT_FOUND on Win7 and
++        // ERROR_RESOURCE_DATA_NOT_FOUND on WinXP.
++        if (GetLastError() == ERROR_FILE_NOT_FOUND ||
++                GetLastError() == ERROR_RESOURCE_DATA_NOT_FOUND) {
++            throw ModuleNotFound();
++        } else {
++            throwWindowsError(
++                (L"GetFileVersionInfoSizeW failed on " + path).c_str());
++        }
++    }
++    std::unique_ptr<char[]> versionBuffer(new char[size]);
++    if (!pGetFileVersionInfoW(path.c_str(), 0, size, versionBuffer.get())) {
++        throwWindowsError((L"GetFileVersionInfoW failed on " + path).c_str());
++    }
++    VS_FIXEDFILEINFO *versionInfo = nullptr;
++    UINT versionInfoSize = 0;
++    if (!pVerQueryValueW(
++                versionBuffer.get(), L"\\",
++                reinterpret_cast<void**>(&versionInfo), &versionInfoSize) ||
++            versionInfo == nullptr ||
++            versionInfoSize != sizeof(VS_FIXEDFILEINFO) ||
++            versionInfo->dwSignature != 0xFEEF04BD) {
++        throwWinptyException((L"VerQueryValueW failed on " + path).c_str());
++    }
++    return *versionInfo;
++}
++
++uint64_t productVersionFromInfo(const VS_FIXEDFILEINFO &info) {
++    return (static_cast<uint64_t>(info.dwProductVersionMS) << 32) |
++           (static_cast<uint64_t>(info.dwProductVersionLS));
++}
++
++uint64_t fileVersionFromInfo(const VS_FIXEDFILEINFO &info) {
++    return (static_cast<uint64_t>(info.dwFileVersionMS) << 32) |
++           (static_cast<uint64_t>(info.dwFileVersionLS));
++}
++
++std::string versionToString(uint64_t version) {
++    StringBuilder b(32);
++    b << ((uint16_t)(version >> 48));
++    b << '.';
++    b << ((uint16_t)(version >> 32));
++    b << '.';
++    b << ((uint16_t)(version >> 16));
++    b << '.';
++    b << ((uint16_t)(version >> 0));
++    return b.str_moved();
++}
++
++} // anonymous namespace
++
++// Returns true for Windows Vista (or Windows Server 2008) or newer.
++bool isAtLeastWindowsVista() {
++    return getWindowsVersion() >= Version(6, 0);
++}
++
++// Returns true for Windows 7 (or Windows Server 2008 R2) or newer.
++bool isAtLeastWindows7() {
++    return getWindowsVersion() >= Version(6, 1);
++}
++
++// Returns true for Windows 8 (or Windows Server 2012) or newer.
++bool isAtLeastWindows8() {
++    return getWindowsVersion() >= Version(6, 2);
++}
++
++#define WINPTY_IA32     1
++#define WINPTY_X64      2
++
++#if defined(_M_IX86) || defined(__i386__)
++#define WINPTY_ARCH WINPTY_IA32
++#elif defined(_M_X64) || defined(__x86_64__)
++#define WINPTY_ARCH WINPTY_X64
++#endif
++
++typedef BOOL WINAPI IsWow64Process_t(HANDLE hProcess, PBOOL Wow64Process);
++
++void dumpWindowsVersion() {
++    if (!isTracingEnabled()) {
++        return;
++    }
++    const auto info = getWindowsVersionInfo();
++    StringBuilder b;
++    b << info.dwMajorVersion << '.' << info.dwMinorVersion
++      << '.' << info.dwBuildNumber << ' '
++      << "SP" << info.wServicePackMajor << '.' << info.wServicePackMinor
++      << ' ';
++    switch (info.wProductType) {
++        case VER_NT_WORKSTATION:        b << "Client"; break;
++        case VER_NT_DOMAIN_CONTROLLER:  b << "DomainController"; break;
++        case VER_NT_SERVER:             b << "Server"; break;
++        default:
++            b << "product=" << info.wProductType; break;
++    }
++    b << ' ';
++#if WINPTY_ARCH == WINPTY_IA32
++    b << "IA32";
++    OsModule kernel32(L"kernel32.dll");
++    IsWow64Process_t *pIsWow64Process =
++        reinterpret_cast<IsWow64Process_t*>(
++            kernel32.proc("IsWow64Process"));
++    if (pIsWow64Process != nullptr) {
++        BOOL result = false;
++        const BOOL success = pIsWow64Process(GetCurrentProcess(), &result);
++        if (!success) {
++            b << " WOW64:error";
++        } else if (success && result) {
++            b << " WOW64";
++        }
++    } else {
++        b << " WOW64:missingapi";
++    }
++#elif WINPTY_ARCH == WINPTY_X64
++    b << "X64";
++#endif
++    const auto dllVersion = [](const wchar_t *dllPath) -> std::string {
++        try {
++            const auto info = getFixedFileInfo(dllPath);
++            StringBuilder fb(64);
++            fb << utf8FromWide(dllPath) << ':';
++            fb << "F:" << versionToString(fileVersionFromInfo(info)) << '/'
++               << "P:" << versionToString(productVersionFromInfo(info));
++            return fb.str_moved();
++        } catch (const ModuleNotFound&) {
++            return utf8FromWide(dllPath) + ":none";
++        } catch (const WinptyException &e) {
++            trace("Error getting %s version: %s",
++                utf8FromWide(dllPath).c_str(), utf8FromWide(e.what()).c_str());
++            return utf8FromWide(dllPath) + ":error";
++        }
++    };
++    b << ' ' << dllVersion(L"kernel32.dll");
++    // ConEmu provides a DLL that hooks many Windows APIs, especially console
++    // APIs.  Its existence and version number could be useful in debugging.
++#if WINPTY_ARCH == WINPTY_IA32
++    b << ' ' << dllVersion(L"ConEmuHk.dll");
++#elif WINPTY_ARCH == WINPTY_X64
++    b << ' ' << dllVersion(L"ConEmuHk64.dll");
++#endif
++    trace("Windows version: %s", b.c_str());
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a80798417ebf525621ad0ea28f0831aec81c3447
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,29 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SHARED_WINDOWS_VERSION_H
++#define WINPTY_SHARED_WINDOWS_VERSION_H
++
++bool isAtLeastWindowsVista();
++bool isAtLeastWindows7();
++bool isAtLeastWindows8();
++void dumpWindowsVersion();
++
++#endif // WINPTY_SHARED_WINDOWS_VERSION_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1ff0de475ab11b66f54de168cb02df41a7d50efb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,55 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "WinptyAssert.h"
++
++#include <windows.h>
++#include <stdlib.h>
++
++#include "DebugClient.h"
++
++void assertTrace(const char *file, int line, const char *cond) {
++    trace("Assertion failed: %s, file %s, line %d",
++          cond, file, line);
++}
++
++#ifdef WINPTY_AGENT_ASSERT
++
++void agentShutdown() {
++    HWND hwnd = GetConsoleWindow();
++    if (hwnd != NULL) {
++        PostMessage(hwnd, WM_CLOSE, 0, 0);
++        Sleep(30000);
++        trace("Agent shutdown: WM_CLOSE did not end agent process");
++    } else {
++        trace("Agent shutdown: GetConsoleWindow() is NULL");
++    }
++    // abort() prints a message to the console, and if it is frozen, then the
++    // process would hang, so instead use exit().  (We shouldn't ever get here,
++    // though, because the WM_CLOSE message should have ended this process.)
++    exit(1);
++}
++
++void agentAssertFail(const char *file, int line, const char *cond) {
++    assertTrace(file, line, cond);
++    agentShutdown();
++}
++
++#endif
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b2b8b5e64c6641dcc437f571f5fbaffc7ac7e7d6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,64 @@@
++// Copyright (c) 2011-2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_ASSERT_H
++#define WINPTY_ASSERT_H
++
++#ifdef WINPTY_AGENT_ASSERT
++
++void agentShutdown();
++void agentAssertFail(const char *file, int line, const char *cond);
++
++// Calling the standard assert() function does not work in the agent because
++// the error message would be printed to the console, and the only way the
++// user can see the console is via a working agent!  Moreover, the console may
++// be frozen, so attempting to write to it would block forever.  This custom
++// assert function instead sends the message to the DebugServer, then attempts
++// to close the console, then quietly exits.
++#define ASSERT(cond) \
++    do {                                                    \
++        if (!(cond)) {                                      \
++            agentAssertFail(__FILE__, __LINE__, #cond);     \
++        }                                                   \
++    } while(0)
++
++#else
++
++void assertTrace(const char *file, int line, const char *cond);
++
++// In the other targets, log the assert failure to the debugserver, then fail
++// using the ordinary assert mechanism.  In case assert is compiled out, fail
++// using abort.  The amount of code inlined is unfortunate, but asserts aren't
++// used much outside the agent.
++#include <assert.h>
++#include <stdlib.h>
++#define ASSERT_CONDITION(cond) (false && (cond))
++#define ASSERT(cond) \
++    do {                                            \
++        if (!(cond)) {                              \
++            assertTrace(__FILE__, __LINE__, #cond); \
++            assert(ASSERT_CONDITION(#cond));        \
++            abort();                                \
++        }                                           \
++    } while(0)
++
++#endif
++
++#endif // WINPTY_ASSERT_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d0d48823d2229661293b8af28b669fa8da49db68
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,57 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "WinptyException.h"
++
++#include <memory>
++#include <string>
++
++#include "StringBuilder.h"
++
++namespace {
++
++class ExceptionImpl : public WinptyException {
++public:
++    ExceptionImpl(const wchar_t *what) :
++        m_what(std::make_shared<std::wstring>(what)) {}
++    virtual const wchar_t *what() const WINPTY_NOEXCEPT override {
++        return m_what->c_str();
++    }
++private:
++    // Using a shared_ptr ensures that copying the object raises no exception.
++    std::shared_ptr<std::wstring> m_what;
++};
++
++} // anonymous namespace
++
++void throwWinptyException(const wchar_t *what) {
++    throw ExceptionImpl(what);
++}
++
++void throwWindowsError(const wchar_t *prefix, DWORD errorCode) {
++    WStringBuilder sb(64);
++    if (prefix != nullptr) {
++        sb << prefix << L": ";
++    }
++    // It might make sense to use FormatMessage here, but IIRC, its API is hard
++    // to figure out.
++    sb << L"Windows error " << errorCode;
++    throwWinptyException(sb.c_str());
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ec353369e5bf7f76061e4b2880524d56034b5ffd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,43 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_EXCEPTION_H
++#define WINPTY_EXCEPTION_H
++
++#include <windows.h>
++
++#if defined(__GNUC__)
++#define WINPTY_NOEXCEPT noexcept
++#elif defined(_MSC_VER) && _MSC_VER >= 1900
++#define WINPTY_NOEXCEPT noexcept
++#else
++#define WINPTY_NOEXCEPT
++#endif
++
++class WinptyException {
++public:
++    virtual const wchar_t *what() const WINPTY_NOEXCEPT = 0;
++    virtual ~WinptyException() {}
++};
++
++void throwWinptyException(const wchar_t *what);
++void throwWindowsError(const wchar_t *prefix, DWORD error=GetLastError());
++
++#endif // WINPTY_EXCEPTION_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..76bb8a584d28b64f8065a8a83995e42de8806ff5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,42 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "WinptyVersion.h"
++
++#include <stdio.h>
++#include <string.h>
++
++#include "DebugClient.h"
++
++// This header is auto-generated by either the Makefile (Unix) or
++// UpdateGenVersion.bat (gyp).  It is placed in a 'gen' directory, which is
++// added to the search path.
++#include "GenVersion.h"
++
++void dumpVersionToStdout() {
++    printf("winpty version %s\n", GenVersion_Version);
++    printf("commit %s\n", GenVersion_Commit);
++}
++
++void dumpVersionToTrace() {
++    trace("winpty version %s (commit %s)",
++        GenVersion_Version,
++        GenVersion_Commit);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e6224d7b84725f8a67b129591b6f1abe4e762fae
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,27 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_VERSION_H
++#define WINPTY_VERSION_H
++
++void dumpVersionToStdout();
++void dumpVersionToTrace();
++
++#endif // WINPTY_VERSION_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e716f245e8c6367654bcbccb916cceafe0556eb6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,99 @@@
++// Copyright (c) 2016 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef WINPTY_SNPRINTF_H
++#define WINPTY_SNPRINTF_H
++
++#include <stdarg.h>
++#include <stdio.h>
++#include <stdlib.h>
++
++#include "WinptyAssert.h"
++
++#if defined(__CYGWIN__) || defined(__MSYS__)
++#define WINPTY_SNPRINTF_FORMAT(fmtarg, vararg) \
++    __attribute__((format(printf, (fmtarg), ((vararg)))))
++#elif defined(__GNUC__)
++#define WINPTY_SNPRINTF_FORMAT(fmtarg, vararg) \
++    __attribute__((format(ms_printf, (fmtarg), ((vararg)))))
++#else
++#define WINPTY_SNPRINTF_FORMAT(fmtarg, vararg)
++#endif
++
++// Returns a value between 0 and size - 1 (inclusive) on success.  Returns -1
++// on failure (including truncation).  The output buffer is always
++// NUL-terminated.
++inline int
++winpty_vsnprintf(char *out, size_t size, const char *fmt, va_list ap) {
++    ASSERT(size > 0);
++    out[0] = '\0';
++#if defined(_MSC_VER) && _MSC_VER < 1900
++    // MSVC 2015 added a C99-conforming vsnprintf.
++    int count = _vsnprintf_s(out, size, _TRUNCATE, fmt, ap);
++#else
++    // MinGW configurations frequently provide a vsnprintf function that simply
++    // calls one of the MS _vsnprintf* functions, which are not C99 conformant.
++    int count = vsnprintf(out, size, fmt, ap);
++#endif
++    if (count < 0 || static_cast<size_t>(count) >= size) {
++        // On truncation, some *printf* implementations return the
++        // non-truncated size, but other implementations returns -1.  Return
++        // -1 for consistency.
++        count = -1;
++        // Guarantee NUL termination.
++        out[size - 1] = '\0';
++    } else {
++        // Guarantee NUL termination.
++        out[count] = '\0';
++    }
++    return count;
++}
++
++// Wraps winpty_vsnprintf.
++inline int winpty_snprintf(char *out, size_t size, const char *fmt, ...)
++    WINPTY_SNPRINTF_FORMAT(3, 4);
++inline int winpty_snprintf(char *out, size_t size, const char *fmt, ...) {
++    va_list ap;
++    va_start(ap, fmt);
++    const int count = winpty_vsnprintf(out, size, fmt, ap);
++    va_end(ap);
++    return count;
++}
++
++// Wraps winpty_vsnprintf with automatic size determination.
++template <size_t size>
++int winpty_vsnprintf(char (&out)[size], const char *fmt, va_list ap) {
++    return winpty_vsnprintf(out, size, fmt, ap);
++}
++
++// Wraps winpty_vsnprintf with automatic size determination.
++template <size_t size>
++int winpty_snprintf(char (&out)[size], const char *fmt, ...)
++    WINPTY_SNPRINTF_FORMAT(2, 3);
++template <size_t size>
++int winpty_snprintf(char (&out)[size], const char *fmt, ...) {
++    va_list ap;
++    va_start(ap, fmt);
++    const int count = winpty_vsnprintf(out, size, fmt, ap);
++    va_end(ap);
++    return count;
++}
++
++#endif // WINPTY_SNPRINTF_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9ae8031b084bb9f27ba186807604c6bfb33b01e7
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,5 @@@
++include src/agent/subdir.mk
++include src/debugserver/subdir.mk
++include src/libwinpty/subdir.mk
++include src/tests/subdir.mk
++include src/unix-adapter/subdir.mk
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..18799c4a5a00837dfaf46130064821302fac6902
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,28 @@@
++# Copyright (c) 2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++build/%.exe : src/tests/%.cc build/winpty.dll
++      $(info Building $@)
++      @$(MINGW_CXX) $(MINGW_CXXFLAGS) $(MINGW_LDFLAGS) -o $@ $^
++
++TEST_PROGRAMS = \
++        build/trivial_test.exe
++
++-include $(TEST_PROGRAMS:.exe=.d)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2188a4befb1960fb9f147f6aefc6dedab73f3e46
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,158 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include <windows.h>
++
++#include <cassert>
++#include <cctype>
++#include <cstdio>
++#include <cstdlib>
++#include <cwchar>
++#include <vector>
++
++#include "../include/winpty.h"
++#include "../shared/DebugClient.h"
++
++static std::vector<unsigned char> filterContent(
++        const std::vector<unsigned char> &content) {
++    std::vector<unsigned char> result;
++    auto it = content.begin();
++    const auto itEnd = content.end();
++    while (it < itEnd) {
++        if (*it == '\r') {
++            // Filter out carriage returns.  Sometimes the output starts with
++            // a single CR; other times, it has multiple CRs.
++            it++;
++        } else if (*it == '\x1b' && (it + 1) < itEnd && *(it + 1) == '[') {
++            // Filter out escape sequences.  They have no interior letters and
++            // end with a single letter.
++            it += 2;
++            while (it < itEnd && !isalpha(*it)) {
++                it++;
++            }
++            it++;
++        } else {
++            // Let everything else through.
++            result.push_back(*it);
++            it++;
++        }
++    }
++    return result;
++}
++
++// Read bytes from the non-overlapped file handle until the file is closed or
++// until an I/O error occurs.
++static std::vector<unsigned char> readAll(HANDLE handle) {
++    unsigned char buf[1024];
++    std::vector<unsigned char> result;
++    while (true) {
++        DWORD amount = 0;
++        BOOL ret = ReadFile(handle, buf, sizeof(buf), &amount, nullptr);
++        if (!ret || amount == 0) {
++            break;
++        }
++        result.insert(result.end(), buf, buf + amount);
++    }
++    return result;
++}
++
++static void parentTest() {
++    wchar_t program[1024];
++    wchar_t cmdline[1024];
++    GetModuleFileNameW(nullptr, program, 1024);
++
++    {
++        // XXX: We'd like to use swprintf, which is part of C99 and takes a
++        // size_t maxlen argument.  MinGW-w64 has this function, as does MSVC.
++        // The old MinGW doesn't, though -- instead, it apparently provides an
++        // swprintf taking no maxlen argument.  This *might* be a regression?
++        // (There is also no swnprintf, but that function is obsolescent with a
++        // correct swprintf, and it isn't in POSIX or ISO C.)
++        //
++        // Visual C++ 6 also provided this non-conformant swprintf, and I'm
++        // guessing MSVCRT.DLL does too.  (My impression is that the old MinGW
++        // prefers to rely on MSVCRT.DLL for convenience?)
++        //
++        // I could compile differently for old MinGW, but what if it fixes its
++        // function later?  Instead, use a workaround.  It's starting to make
++        // sense to drop MinGW support in favor of MinGW-w64.  This is too
++        // annoying.
++        //
++        // grepbait: OLD-MINGW / WINPTY_TARGET_MSYS1
++        cmdline[0] = L'\0';
++        wcscat(cmdline, L"\"");
++        wcscat(cmdline, program);
++        wcscat(cmdline, L"\" CHILD");
++    }
++    // swnprintf(cmdline, sizeof(cmdline) / sizeof(cmdline[0]),
++    //           L"\"%ls\" CHILD", program);
++
++    auto agentCfg = winpty_config_new(0, nullptr);
++    assert(agentCfg != nullptr);
++    auto pty = winpty_open(agentCfg, nullptr);
++    assert(pty != nullptr);
++    winpty_config_free(agentCfg);
++
++    HANDLE conin = CreateFileW(
++        winpty_conin_name(pty),
++        GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
++    HANDLE conout = CreateFileW(
++        winpty_conout_name(pty),
++        GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
++    assert(conin != INVALID_HANDLE_VALUE);
++    assert(conout != INVALID_HANDLE_VALUE);
++
++    auto spawnCfg = winpty_spawn_config_new(
++            WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN, program, cmdline,
++            nullptr, nullptr, nullptr);
++    assert(spawnCfg != nullptr);
++    HANDLE process = nullptr;
++    BOOL spawnSuccess = winpty_spawn(
++        pty, spawnCfg, &process, nullptr, nullptr, nullptr);
++    assert(spawnSuccess && process != nullptr);
++
++    auto content = readAll(conout);
++    content = filterContent(content);
++
++    std::vector<unsigned char> expectedContent = {
++        'H', 'I', '\n', 'X', 'Y', '\n'
++    };
++    DWORD exitCode = 0;
++    assert(GetExitCodeProcess(process, &exitCode) && exitCode == 42);
++    CloseHandle(process);
++    CloseHandle(conin);
++    CloseHandle(conout);
++    assert(content == expectedContent);
++    winpty_free(pty);
++}
++
++static void childTest() {
++    printf("HI\nXY\n");
++    exit(42);
++}
++
++int main(int argc, char *argv[]) {
++    if (argc == 1) {
++        parentTest();
++    } else {
++        childTest();
++    }
++    return 0;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..39f1e096850757a8c5fc4d8d524a53701454e45a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,114 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "InputHandler.h"
++
++#include <assert.h>
++#include <errno.h>
++#include <stdio.h>
++#include <sys/select.h>
++#include <unistd.h>
++
++#include <algorithm>
++#include <vector>
++
++#include "../shared/DebugClient.h"
++#include "Util.h"
++#include "WakeupFd.h"
++
++InputHandler::InputHandler(
++        HANDLE conin, int inputfd, WakeupFd &completionWakeup) :
++    m_conin(conin),
++    m_inputfd(inputfd),
++    m_completionWakeup(completionWakeup),
++    m_threadHasBeenJoined(false),
++    m_shouldShutdown(0),
++    m_threadCompleted(0)
++{
++    pthread_create(&m_thread, NULL, InputHandler::threadProcS, this);
++}
++
++void InputHandler::shutdown() {
++    startShutdown();
++    if (!m_threadHasBeenJoined) {
++        int ret = pthread_join(m_thread, NULL);
++        assert(ret == 0 && "pthread_join failed");
++        m_threadHasBeenJoined = true;
++    }
++}
++
++void InputHandler::threadProc() {
++    std::vector<char> buffer(4096);
++    fd_set readfds;
++    FD_ZERO(&readfds);
++    while (true) {
++        // Handle shutdown.
++        m_wakeup.reset();
++        if (m_shouldShutdown) {
++            trace("InputHandler: shutting down");
++            break;
++        }
++
++        // Block until data arrives.
++        {
++            const int max_fd = std::max(m_inputfd, m_wakeup.fd());
++            FD_SET(m_inputfd, &readfds);
++            FD_SET(m_wakeup.fd(), &readfds);
++            selectWrapper("InputHandler", max_fd + 1, &readfds);
++            if (!FD_ISSET(m_inputfd, &readfds)) {
++                continue;
++            }
++        }
++
++        const int numRead = read(m_inputfd, &buffer[0], buffer.size());
++        if (numRead == -1 && errno == EINTR) {
++            // Apparently, this read is interrupted on Cygwin 1.7 by a SIGWINCH
++            // signal even though I set the SA_RESTART flag on the handler.
++            continue;
++        }
++
++        // tty is closed, or the read failed for some unexpected reason.
++        if (numRead <= 0) {
++            trace("InputHandler: tty read failed: numRead=%d", numRead);
++            break;
++        }
++
++        DWORD written = 0;
++        BOOL ret = WriteFile(m_conin,
++                             &buffer[0], numRead,
++                             &written, NULL);
++        if (!ret || written != static_cast<DWORD>(numRead)) {
++            if (!ret && GetLastError() == ERROR_BROKEN_PIPE) {
++                trace("InputHandler: pipe closed: written=%u",
++                    static_cast<unsigned int>(written));
++            } else {
++                trace("InputHandler: write failed: "
++                    "ret=%d lastError=0x%x numRead=%d written=%u",
++                    ret,
++                    static_cast<unsigned int>(GetLastError()),
++                    numRead,
++                    static_cast<unsigned int>(written));
++            }
++            break;
++        }
++    }
++    m_threadCompleted = 1;
++    m_completionWakeup.set();
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..9c3f540d6349e229c6159659a959b1bc490c8736
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,56 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef UNIX_ADAPTER_INPUT_HANDLER_H
++#define UNIX_ADAPTER_INPUT_HANDLER_H
++
++#include <windows.h>
++#include <pthread.h>
++#include <signal.h>
++
++#include "WakeupFd.h"
++
++// Connect a Cygwin blocking fd to winpty CONIN.
++class InputHandler {
++public:
++    InputHandler(HANDLE conin, int inputfd, WakeupFd &completionWakeup);
++    ~InputHandler() { shutdown(); }
++    bool isComplete() { return m_threadCompleted; }
++    void startShutdown() { m_shouldShutdown = 1; m_wakeup.set(); }
++    void shutdown();
++
++private:
++    static void *threadProcS(void *pvthis) {
++        reinterpret_cast<InputHandler*>(pvthis)->threadProc();
++        return NULL;
++    }
++    void threadProc();
++
++    HANDLE m_conin;
++    int m_inputfd;
++    pthread_t m_thread;
++    WakeupFd &m_completionWakeup;
++    WakeupFd m_wakeup;
++    bool m_threadHasBeenJoined;
++    volatile sig_atomic_t m_shouldShutdown;
++    volatile sig_atomic_t m_threadCompleted;
++};
++
++#endif // UNIX_ADAPTER_INPUT_HANDLER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..573b8adced39eaf5671ea142917d047a6bccb18f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,80 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "OutputHandler.h"
++
++#include <assert.h>
++#include <errno.h>
++#include <sys/select.h>
++#include <unistd.h>
++
++#include <algorithm>
++#include <vector>
++
++#include "../shared/DebugClient.h"
++#include "Util.h"
++#include "WakeupFd.h"
++
++OutputHandler::OutputHandler(
++        HANDLE conout, int outputfd, WakeupFd &completionWakeup) :
++    m_conout(conout),
++    m_outputfd(outputfd),
++    m_completionWakeup(completionWakeup),
++    m_threadHasBeenJoined(false),
++    m_threadCompleted(0)
++{
++    pthread_create(&m_thread, NULL, OutputHandler::threadProcS, this);
++}
++
++void OutputHandler::shutdown() {
++    if (!m_threadHasBeenJoined) {
++        int ret = pthread_join(m_thread, NULL);
++        assert(ret == 0 && "pthread_join failed");
++        m_threadHasBeenJoined = true;
++    }
++}
++
++void OutputHandler::threadProc() {
++    std::vector<char> buffer(4096);
++    while (true) {
++        DWORD numRead = 0;
++        BOOL ret = ReadFile(m_conout,
++                            &buffer[0], buffer.size(),
++                            &numRead, NULL);
++        if (!ret || numRead == 0) {
++            if (!ret && GetLastError() == ERROR_BROKEN_PIPE) {
++                trace("OutputHandler: pipe closed: numRead=%u",
++                    static_cast<unsigned int>(numRead));
++            } else {
++                trace("OutputHandler: read failed: "
++                    "ret=%d lastError=0x%x numRead=%u",
++                    ret,
++                    static_cast<unsigned int>(GetLastError()),
++                    static_cast<unsigned int>(numRead));
++            }
++            break;
++        }
++        if (!writeAll(m_outputfd, &buffer[0], numRead)) {
++            break;
++        }
++    }
++    m_threadCompleted = 1;
++    m_completionWakeup.set();
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..48241c5538705954a0db82171d8caa0065e70693
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,53 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef UNIX_ADAPTER_OUTPUT_HANDLER_H
++#define UNIX_ADAPTER_OUTPUT_HANDLER_H
++
++#include <windows.h>
++#include <pthread.h>
++#include <signal.h>
++
++#include "WakeupFd.h"
++
++// Connect winpty CONOUT/CONERR to a Cygwin blocking fd.
++class OutputHandler {
++public:
++    OutputHandler(HANDLE conout, int outputfd, WakeupFd &completionWakeup);
++    ~OutputHandler() { shutdown(); }
++    bool isComplete() { return m_threadCompleted; }
++    void shutdown();
++
++private:
++    static void *threadProcS(void *pvthis) {
++        reinterpret_cast<OutputHandler*>(pvthis)->threadProc();
++        return NULL;
++    }
++    void threadProc();
++
++    HANDLE m_conout;
++    int m_outputfd;
++    pthread_t m_thread;
++    WakeupFd &m_completionWakeup;
++    bool m_threadHasBeenJoined;
++    volatile sig_atomic_t m_threadCompleted;
++};
++
++#endif // UNIX_ADAPTER_OUTPUT_HANDLER_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e13f84a5299b16638300f37e4902b041224dcbaf
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,86 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "Util.h"
++
++#include <assert.h>
++#include <errno.h>
++#include <stdio.h>
++#include <string.h>
++#include <unistd.h>
++
++#include "../shared/DebugClient.h"
++
++// Write the entire buffer, restarting it as necessary.
++bool writeAll(int fd, const void *buffer, size_t size) {
++    size_t written = 0;
++    while (written < size) {
++        int ret = write(fd,
++                        reinterpret_cast<const char*>(buffer) + written,
++                        size - written);
++        if (ret == -1 && errno == EINTR) {
++            continue;
++        }
++        if (ret <= 0) {
++            trace("write failed: "
++                "fd=%d errno=%d size=%u written=%d ret=%d",
++                fd,
++                errno,
++                static_cast<unsigned int>(size),
++                static_cast<unsigned int>(written),
++                ret);
++            return false;
++        }
++        assert(static_cast<size_t>(ret) <= size - written);
++        written += ret;
++    }
++    assert(written == size);
++    return true;
++}
++
++bool writeStr(int fd, const char *str) {
++    return writeAll(fd, str, strlen(str));
++}
++
++void selectWrapper(const char *diagName, int nfds, fd_set *readfds) {
++    int ret = select(nfds, readfds, NULL, NULL, NULL);
++    if (ret < 0) {
++        if (errno == EINTR) {
++            FD_ZERO(readfds);
++            return;
++        }
++#ifdef WINPTY_TARGET_MSYS1
++        // The select system call sometimes fails with EAGAIN instead of EINTR.
++        // This apparantly only happens with the old Cygwin fork "MSYS" used in
++        // the mingw.org project.  select is not supposed to fail with EAGAIN,
++        // and EAGAIN does not make much sense as an error code.  (The whole
++        // point of select is to block.)
++        if (errno == EAGAIN) {
++            trace("%s select returned EAGAIN: interpreting like EINTR",
++                diagName);
++            FD_ZERO(readfds);
++            return;
++        }
++#endif
++        fprintf(stderr, "Internal error: %s select failed: "
++            "error %d", diagName, errno);
++        abort();
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cadb4c82a96fdc1f9dc0ac6a4bf0a0b1773cdab8
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,31 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef UNIX_ADAPTER_UTIL_H
++#define UNIX_ADAPTER_UTIL_H
++
++#include <stdlib.h>
++#include <sys/select.h>
++
++bool writeAll(int fd, const void *buffer, size_t size);
++bool writeStr(int fd, const char *str);
++void selectWrapper(const char *diagName, int nfds, fd_set *readfds);
++
++#endif // UNIX_ADAPTER_UTIL_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6b473790153470cf805bf13239e0701a83a40b60
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,70 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#include "WakeupFd.h"
++
++#include <errno.h>
++#include <fcntl.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <unistd.h>
++
++static void setFdNonBlock(int fd) {
++    int status = fcntl(fd, F_GETFL);
++    fcntl(fd, F_SETFL, status | O_NONBLOCK);
++}
++
++WakeupFd::WakeupFd() {
++    int pipeFd[2];
++    if (pipe(pipeFd) != 0) {
++        perror("Could not create internal wakeup pipe");
++        abort();
++    }
++    m_pipeReadFd = pipeFd[0];
++    m_pipeWriteFd = pipeFd[1];
++    setFdNonBlock(m_pipeReadFd);
++    setFdNonBlock(m_pipeWriteFd);
++}
++
++WakeupFd::~WakeupFd() {
++    close(m_pipeReadFd);
++    close(m_pipeWriteFd);
++}
++
++void WakeupFd::set() {
++    char dummy = 0;
++    int ret;
++    do {
++        ret = write(m_pipeWriteFd, &dummy, 1);
++    } while (ret < 0 && errno == EINTR);
++}
++
++void WakeupFd::reset() {
++    char tmpBuf[256];
++    while (true) {
++        int amount = read(m_pipeReadFd, tmpBuf, sizeof(tmpBuf));
++        if (amount < 0 && errno == EAGAIN) {
++            break;
++        } else if (amount <= 0) {
++            perror("error reading from internal wakeup pipe");
++            abort();
++        }
++    }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..dd8d362aa10d72c6cde9938e895c4e88e773c48d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,42 @@@
++// Copyright (c) 2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++#ifndef UNIX_ADAPTER_WAKEUP_FD_H
++#define UNIX_ADAPTER_WAKEUP_FD_H
++
++class WakeupFd {
++public:
++    WakeupFd();
++    ~WakeupFd();
++    int fd()   { return m_pipeReadFd; }
++    void set();
++    void reset();
++
++private:
++    // Do not allow copying the WakeupFd object.
++    WakeupFd(const WakeupFd &other);
++    WakeupFd &operator=(const WakeupFd &other);
++
++private:
++    int m_pipeReadFd;
++    int m_pipeWriteFd;
++};
++
++#endif // UNIX_ADAPTER_WAKEUP_FD_H
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..992cb70e449b778b0044024c120f86611392f603
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,729 @@@
++// Copyright (c) 2011-2015 Ryan Prichard
++//
++// Permission is hereby granted, free of charge, to any person obtaining a copy
++// of this software and associated documentation files (the "Software"), to
++// deal in the Software without restriction, including without limitation the
++// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++// sell copies of the Software, and to permit persons to whom the Software is
++// furnished to do so, subject to the following conditions:
++//
++// The above copyright notice and this permission notice shall be included in
++// all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++// IN THE SOFTWARE.
++
++// MSYS's sys/cygwin.h header only declares cygwin_internal if WINVER is
++// defined, which is defined in windows.h.  Therefore, include windows.h early.
++#include <windows.h>
++
++#include <assert.h>
++#include <cygwin/version.h>
++#include <errno.h>
++#include <signal.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <sys/ioctl.h>
++#include <sys/select.h>
++#include <sys/cygwin.h>
++#include <termios.h>
++#include <unistd.h>
++
++#include <map>
++#include <string>
++#include <utility>
++#include <vector>
++
++#include <winpty.h>
++#include "../shared/DebugClient.h"
++#include "../shared/UnixCtrlChars.h"
++#include "../shared/WinptyVersion.h"
++#include "InputHandler.h"
++#include "OutputHandler.h"
++#include "Util.h"
++#include "WakeupFd.h"
++
++#define CSI "\x1b["
++
++static WakeupFd *g_mainWakeup = NULL;
++
++static WakeupFd &mainWakeup()
++{
++    if (g_mainWakeup == NULL) {
++        static const char msg[] = "Internal error: g_mainWakeup is NULL\r\n";
++        write(STDERR_FILENO, msg, sizeof(msg) - 1);
++        abort();
++    }
++    return *g_mainWakeup;
++}
++
++struct SavedTermiosMode {
++    int count;
++    bool valid[3];
++    termios mode[3];
++};
++
++// Put the input terminal into non-canonical mode.
++static SavedTermiosMode setRawTerminalMode(
++    bool allowNonTtys, bool setStdout, bool setStderr)
++{
++    SavedTermiosMode ret;
++    const char *const kNames[3] = { "stdin", "stdout", "stderr" };
++
++    ret.valid[0] = true;
++    ret.valid[1] = setStdout;
++    ret.valid[2] = setStderr;
++
++    for (int i = 0; i < 3; ++i) {
++        if (!ret.valid[i]) {
++            continue;
++        }
++        if (!isatty(i)) {
++            ret.valid[i] = false;
++            if (!allowNonTtys) {
++                fprintf(stderr, "%s is not a tty\n", kNames[i]);
++                exit(1);
++            }
++        } else {
++            ret.valid[i] = true;
++            if (tcgetattr(i, &ret.mode[i]) < 0) {
++                perror("tcgetattr failed");
++                exit(1);
++            }
++        }
++    }
++
++    if (ret.valid[STDIN_FILENO]) {
++        termios buf;
++        if (tcgetattr(STDIN_FILENO, &buf) < 0) {
++            perror("tcgetattr failed");
++            exit(1);
++        }
++        buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
++        buf.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
++        buf.c_cflag &= ~(CSIZE | PARENB);
++        buf.c_cflag |= CS8;
++        buf.c_cc[VMIN] = 1;  // blocking read
++        buf.c_cc[VTIME] = 0;
++        if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &buf) < 0) {
++            fprintf(stderr, "tcsetattr failed\n");
++            exit(1);
++        }
++    }
++
++    for (int i = STDOUT_FILENO; i <= STDERR_FILENO; ++i) {
++        if (!ret.valid[i]) {
++            continue;
++        }
++        termios buf;
++        if (tcgetattr(i, &buf) < 0) {
++            perror("tcgetattr failed");
++            exit(1);
++        }
++        buf.c_cflag &= ~(CSIZE | PARENB);
++        buf.c_cflag |= CS8;
++        buf.c_oflag &= ~OPOST;
++        if (tcsetattr(i, TCSAFLUSH, &buf) < 0) {
++            fprintf(stderr, "tcsetattr failed\n");
++            exit(1);
++        }
++    }
++
++    return ret;
++}
++
++static void restoreTerminalMode(const SavedTermiosMode &original)
++{
++    for (int i = 0; i < 3; ++i) {
++        if (!original.valid[i]) {
++            continue;
++        }
++        if (tcsetattr(i, TCSAFLUSH, &original.mode[i]) < 0) {
++            perror("error restoring terminal mode");
++            exit(1);
++        }
++    }
++}
++
++static void debugShowKey(bool allowNonTtys)
++{
++    printf("\nPress any keys -- Ctrl-D exits\n\n");
++    const SavedTermiosMode saved =
++        setRawTerminalMode(allowNonTtys, false, false);
++    char buf[128];
++    while (true) {
++        const ssize_t len = read(STDIN_FILENO, buf, sizeof(buf));
++        if (len <= 0) {
++            break;
++        }
++        for (int i = 0; i < len; ++i) {
++            char ctrl = decodeUnixCtrlChar(buf[i]);
++            if (ctrl == '\0') {
++                putchar(buf[i]);
++            } else {
++                putchar('^');
++                putchar(ctrl);
++            }
++        }
++        for (int i = 0; i < len; ++i) {
++            unsigned char uch = buf[i];
++            printf("\t%3d %04o 0x%02x\n", uch, uch, uch);
++            fflush(stdout);
++        }
++        if (buf[0] == 4) {
++            // Ctrl-D
++            break;
++        }
++    }
++    restoreTerminalMode(saved);
++}
++
++static void terminalResized(int signo)
++{
++    mainWakeup().set();
++}
++
++static void registerResizeSignalHandler()
++{
++    struct sigaction resizeSigAct;
++    memset(&resizeSigAct, 0, sizeof(resizeSigAct));
++    resizeSigAct.sa_handler = terminalResized;
++    resizeSigAct.sa_flags = SA_RESTART;
++    sigaction(SIGWINCH, &resizeSigAct, NULL);
++}
++
++// Convert the path to a Win32 path if it is a POSIX path, and convert slashes
++// to backslashes.
++static std::string convertPosixPathToWin(const std::string &path)
++{
++    char *tmp;
++#if defined(CYGWIN_VERSION_CYGWIN_CONV) && \
++        CYGWIN_VERSION_API_MINOR >= CYGWIN_VERSION_CYGWIN_CONV
++    // MSYS2 and versions of Cygwin released after 2009 or so use this API.
++    // The original MSYS still lacks this API.
++    ssize_t newSize = cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
++                                       path.c_str(), NULL, 0);
++    assert(newSize >= 0);
++    tmp = new char[newSize + 1];
++    ssize_t success = cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
++                                       path.c_str(), tmp, newSize + 1);
++    assert(success == 0);
++#else
++    // In the current Cygwin header file, this API is documented as deprecated
++    // because it's restricted to paths of MAX_PATH length.  In the CVS version
++    // of MSYS, the newer API doesn't exist, and this older API is implemented
++    // using msys_p2w, which seems like it would handle paths larger than
++    // MAX_PATH, but there's no way to query how large the new path is.
++    // Hopefully, this is large enough.
++    tmp = new char[MAX_PATH + path.size()];
++    cygwin_conv_to_win32_path(path.c_str(), tmp);
++#endif
++    for (int i = 0; tmp[i] != '\0'; ++i) {
++        if (tmp[i] == '/')
++            tmp[i] = '\\';
++    }
++    std::string ret(tmp);
++    delete [] tmp;
++    return ret;
++}
++
++static std::string resolvePath(const std::string &path)
++{
++    char ret[PATH_MAX];
++    ret[0] = '\0';
++    if (realpath(path.c_str(), ret) != ret) {
++        return std::string();
++    }
++    return ret;
++}
++
++template <size_t N>
++static bool endsWith(const std::string &path, const char (&suf)[N])
++{
++    const size_t suffixLen = N - 1;
++    char actualSuf[N];
++    if (path.size() < suffixLen) {
++        return false;
++    }
++    strcpy(actualSuf, &path.c_str()[path.size() - suffixLen]);
++    for (size_t i = 0; i < suffixLen; ++i) {
++        actualSuf[i] = tolower(actualSuf[i]);
++    }
++    return !strcmp(actualSuf, suf);
++}
++
++static std::string findProgram(
++    const char *winptyProgName,
++    const std::string &prog)
++{
++    std::string candidate;
++    if (prog.find('/') == std::string::npos &&
++            prog.find('\\') == std::string::npos) {
++        // XXX: It would be nice to use a lambda here (once/if old MSYS support
++        // is dropped).
++        // Search the PATH.
++        const char *const pathVar = getenv("PATH");
++        const std::string pathList(pathVar ? pathVar : "");
++        size_t elpos = 0;
++        while (true) {
++            const size_t elend = pathList.find(':', elpos);
++            candidate = pathList.substr(elpos, elend - elpos);
++            if (!candidate.empty() && *(candidate.end() - 1) != '/') {
++                candidate += '/';
++            }
++            candidate += prog;
++            candidate = resolvePath(candidate);
++            if (!candidate.empty()) {
++                int perm = X_OK;
++                if (endsWith(candidate, ".bat") || endsWith(candidate, ".cmd")) {
++#ifdef __MSYS__
++                    // In MSYS/MSYS2, batch files don't have the execute bit
++                    // set, so just check that they're readable.
++                    perm = R_OK;
++#endif
++                } else if (endsWith(candidate, ".com") || endsWith(candidate, ".exe")) {
++                    // Do nothing.
++                } else {
++                    // Make the exe extension explicit so that we don't try to
++                    // run shell scripts with CreateProcess/winpty_spawn.
++                    candidate += ".exe";
++                }
++                if (!access(candidate.c_str(), perm)) {
++                    break;
++                }
++            }
++            if (elend == std::string::npos) {
++                fprintf(stderr, "%s: error: cannot start '%s': Not found in PATH\n",
++                    winptyProgName, prog.c_str());
++                exit(1);
++            } else {
++                elpos = elend + 1;
++            }
++        }
++    } else {
++        candidate = resolvePath(prog);
++        if (candidate.empty()) {
++            std::string errstr(strerror(errno));
++            fprintf(stderr, "%s: error: cannot start '%s': %s\n",
++                winptyProgName, prog.c_str(), errstr.c_str());
++            exit(1);
++        }
++    }
++    return convertPosixPathToWin(candidate);
++}
++
++// Convert argc/argv into a Win32 command-line following the escaping convention
++// documented on MSDN.  (e.g. see CommandLineToArgvW documentation)
++static std::string argvToCommandLine(const std::vector<std::string> &argv)
++{
++    std::string result;
++    for (size_t argIndex = 0; argIndex < argv.size(); ++argIndex) {
++        if (argIndex > 0)
++            result.push_back(' ');
++        const char *arg = argv[argIndex].c_str();
++        const bool quote =
++            strchr(arg, ' ') != NULL ||
++            strchr(arg, '\t') != NULL ||
++            *arg == '\0';
++        if (quote)
++            result.push_back('\"');
++        int bsCount = 0;
++        for (const char *p = arg; *p != '\0'; ++p) {
++            if (*p == '\\') {
++                bsCount++;
++            } else if (*p == '\"') {
++                result.append(bsCount * 2 + 1, '\\');
++                result.push_back('\"');
++                bsCount = 0;
++            } else {
++                result.append(bsCount, '\\');
++                bsCount = 0;
++                result.push_back(*p);
++            }
++        }
++        if (quote) {
++            result.append(bsCount * 2, '\\');
++            result.push_back('\"');
++        } else {
++            result.append(bsCount, '\\');
++        }
++    }
++    return result;
++}
++
++static wchar_t *heapMbsToWcs(const char *text)
++{
++    // Calling mbstowcs with a NULL first argument seems to be broken on MSYS.
++    // Instead of returning the size of the converted string, it returns 0.
++    // Using strlen(text) * 2 is probably big enough.
++    size_t maxLen = strlen(text) * 2 + 1;
++    wchar_t *ret = new wchar_t[maxLen];
++    size_t len = mbstowcs(ret, text, maxLen);
++    assert(len != (size_t)-1 && len < maxLen);
++    return ret;
++}
++
++static char *heapWcsToMbs(const wchar_t *text)
++{
++    // Calling wcstombs with a NULL first argument seems to be broken on MSYS.
++    // Instead of returning the size of the converted string, it returns 0.
++    // Using wcslen(text) * 3 is big enough for UTF-8 and probably other
++    // encodings.  For UTF-8, codepoints that fit in a single wchar
++    // (U+0000 to U+FFFF) are encoded using 1-3 bytes.  The remaining code
++    // points needs two wchar's and are encoded using 4 bytes.
++    size_t maxLen = wcslen(text) * 3 + 1;
++    char *ret = new char[maxLen];
++    size_t len = wcstombs(ret, text, maxLen);
++    if (len == (size_t)-1 || len >= maxLen) {
++        delete [] ret;
++        return NULL;
++    } else {
++        return ret;
++    }
++}
++
++static std::string wcsToMbs(const wchar_t *text)
++{
++    std::string ret;
++    const char *ptr = heapWcsToMbs(text);
++    if (ptr != NULL) {
++        ret = ptr;
++        delete [] ptr;
++    }
++    return ret;
++}
++
++void setupWin32Environment()
++{
++    std::map<std::string, std::string> varsToCopy;
++    const char *vars[] = {
++        "WINPTY_DEBUG",
++        "WINPTY_SHOW_CONSOLE",
++        NULL
++    };
++    for (int i = 0; vars[i] != NULL; ++i) {
++        const char *cstr = getenv(vars[i]);
++        if (cstr != NULL && cstr[0] != '\0') {
++            varsToCopy[vars[i]] = cstr;
++        }
++    }
++
++#if defined(__MSYS__) && CYGWIN_VERSION_API_MINOR >= 48 || \
++        !defined(__MSYS__) && CYGWIN_VERSION_API_MINOR >= 153
++    // Use CW_SYNC_WINENV to copy the Unix environment to the Win32
++    // environment.  The command performs special translation on some variables
++    // (such as PATH and TMP).  It also copies the debugging environment
++    // variables.
++    //
++    // Note that the API minor versions have diverged in Cygwin and MSYS.
++    // CW_SYNC_WINENV was added to Cygwin in version 153.  (Cygwin's
++    // include/cygwin/version.h says that CW_SETUP_WINENV was added in 153.
++    // The flag was renamed 8 days after it was added, but the API docs weren't
++    // updated.)  The flag was added to MSYS in version 48.
++    //
++    // Also, in my limited testing, this call seems to be necessary with Cygwin
++    // but unnecessary with MSYS.  Perhaps MSYS is automatically syncing the
++    // Unix environment with the Win32 environment before starting console.exe?
++    // It shouldn't hurt to call it for MSYS.
++    cygwin_internal(CW_SYNC_WINENV);
++#endif
++
++    // Copy debugging environment variables from the Cygwin environment
++    // to the Win32 environment so the agent will inherit it.
++    for (std::map<std::string, std::string>::iterator it = varsToCopy.begin();
++            it != varsToCopy.end();
++            ++it) {
++        wchar_t *nameW = heapMbsToWcs(it->first.c_str());
++        wchar_t *valueW = heapMbsToWcs(it->second.c_str());
++        SetEnvironmentVariableW(nameW, valueW);
++        delete [] nameW;
++        delete [] valueW;
++    }
++
++    // Clear the TERM variable.  The child process's immediate console/terminal
++    // environment is a Windows console, not the terminal that winpty is
++    // communicating with.  Leaving the TERM variable set can break programs in
++    // various ways.  (e.g. arrows keys broken in Cygwin less, IronPython's
++    // help(...) function doesn't start, misc programs decide they should
++    // output color escape codes on pre-Win10).  See
++    // https://github.com/rprichard/winpty/issues/43.
++    SetEnvironmentVariableW(L"TERM", NULL);
++}
++
++static void usage(const char *program, int exitCode)
++{
++    printf("Usage: %s [options] [--] program [args]\n", program);
++    printf("\n");
++    printf("Options:\n");
++    printf("  -h, --help  Show this help message\n");
++    printf("  --mouse     Enable terminal mouse input\n");
++    printf("  --showkey   Dump STDIN escape sequences\n");
++    printf("  --version   Show the winpty version number\n");
++    exit(exitCode);
++}
++
++struct Arguments {
++    std::vector<std::string> childArgv;
++    bool mouseInput;
++    bool testAllowNonTtys;
++    bool testConerr;
++    bool testPlainOutput;
++    bool testColorEscapes;
++};
++
++static void parseArguments(int argc, char *argv[], Arguments &out)
++{
++    out.mouseInput = false;
++    out.testAllowNonTtys = false;
++    out.testConerr = false;
++    out.testPlainOutput = false;
++    out.testColorEscapes = false;
++    bool doShowKeys = false;
++    const char *const program = argc >= 1 ? argv[0] : "<program>";
++    int argi = 1;
++    while (argi < argc) {
++        std::string arg(argv[argi++]);
++        if (arg.size() >= 1 && arg[0] == '-') {
++            if (arg == "-h" || arg == "--help") {
++                usage(program, 0);
++            } else if (arg == "--mouse") {
++                out.mouseInput = true;
++            } else if (arg == "--showkey") {
++                doShowKeys = true;
++            } else if (arg == "--version") {
++                dumpVersionToStdout();
++                exit(0);
++            } else if (arg == "-Xallow-non-tty") {
++                out.testAllowNonTtys = true;
++            } else if (arg == "-Xconerr") {
++                out.testConerr = true;
++            } else if (arg == "-Xplain") {
++                out.testPlainOutput = true;
++            } else if (arg == "-Xcolor") {
++                out.testColorEscapes = true;
++            } else if (arg == "--") {
++                break;
++            } else {
++                fprintf(stderr, "Error: unrecognized option: '%s'\n",
++                    arg.c_str());
++                exit(1);
++            }
++        } else {
++            out.childArgv.push_back(arg);
++            break;
++        }
++    }
++    for (; argi < argc; ++argi) {
++        out.childArgv.push_back(argv[argi]);
++    }
++    if (doShowKeys) {
++        debugShowKey(out.testAllowNonTtys);
++        exit(0);
++    }
++    if (out.childArgv.size() == 0) {
++        usage(program, 1);
++    }
++}
++
++static std::string errorMessageToString(DWORD err)
++{
++    // Use FormatMessageW rather than FormatMessageA, because we want to use
++    // wcstombs to convert to the Cygwin locale, which might not match the
++    // codepage FormatMessageA would use.  We need to convert using wcstombs,
++    // rather than print using %ls, because %ls doesn't work in the original
++    // MSYS.
++    wchar_t *wideMsgPtr = NULL;
++    const DWORD formatRet = FormatMessageW(
++        FORMAT_MESSAGE_FROM_SYSTEM |
++            FORMAT_MESSAGE_ALLOCATE_BUFFER |
++            FORMAT_MESSAGE_IGNORE_INSERTS,
++        NULL,
++        err,
++        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
++        reinterpret_cast<wchar_t*>(&wideMsgPtr),
++        0,
++        NULL);
++    if (formatRet == 0 || wideMsgPtr == NULL) {
++        return std::string();
++    }
++    std::string msg = wcsToMbs(wideMsgPtr);
++    LocalFree(wideMsgPtr);
++    const size_t pos = msg.find_last_not_of(" \r\n\t");
++    if (pos == std::string::npos) {
++        msg.clear();
++    } else {
++        msg.erase(pos + 1);
++    }
++    return msg;
++}
++
++static std::string formatErrorMessage(DWORD err)
++{
++    char buf[64];
++    sprintf(buf, "error %#x", static_cast<unsigned int>(err));
++    std::string ret = errorMessageToString(err);
++    if (ret.empty()) {
++        ret += buf;
++    } else {
++        ret += " (";
++        ret += buf;
++        ret += ")";
++    }
++    return ret;
++}
++
++int main(int argc, char *argv[])
++{
++    setlocale(LC_ALL, "");
++
++    g_mainWakeup = new WakeupFd();
++
++    Arguments args;
++    parseArguments(argc, argv, args);
++
++    setupWin32Environment();
++
++    winsize sz = { 0 };
++    sz.ws_col = 80;
++    sz.ws_row = 25;
++    ioctl(STDIN_FILENO, TIOCGWINSZ, &sz);
++
++    DWORD agentFlags = WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION;
++    if (args.testConerr)        { agentFlags |= WINPTY_FLAG_CONERR; }
++    if (args.testPlainOutput)   { agentFlags |= WINPTY_FLAG_PLAIN_OUTPUT; }
++    if (args.testColorEscapes)  { agentFlags |= WINPTY_FLAG_COLOR_ESCAPES; }
++    winpty_config_t *agentCfg = winpty_config_new(agentFlags, NULL);
++    assert(agentCfg != NULL);
++    winpty_config_set_initial_size(agentCfg, sz.ws_col, sz.ws_row);
++    if (args.mouseInput) {
++        winpty_config_set_mouse_mode(agentCfg, WINPTY_MOUSE_MODE_FORCE);
++    }
++
++    winpty_error_ptr_t openErr = NULL;
++    winpty_t *wp = winpty_open(agentCfg, &openErr);
++    if (wp == NULL) {
++        fprintf(stderr, "Error creating winpty: %s\n",
++            wcsToMbs(winpty_error_msg(openErr)).c_str());
++        exit(1);
++    }
++    winpty_config_free(agentCfg);
++    winpty_error_free(openErr);
++
++    HANDLE conin = CreateFileW(winpty_conin_name(wp), GENERIC_WRITE, 0, NULL,
++                               OPEN_EXISTING, 0, NULL);
++    HANDLE conout = CreateFileW(winpty_conout_name(wp), GENERIC_READ, 0, NULL,
++                                OPEN_EXISTING, 0, NULL);
++    assert(conin != INVALID_HANDLE_VALUE);
++    assert(conout != INVALID_HANDLE_VALUE);
++    HANDLE conerr = NULL;
++    if (args.testConerr) {
++        conerr = CreateFileW(winpty_conerr_name(wp), GENERIC_READ, 0, NULL,
++                             OPEN_EXISTING, 0, NULL);
++        assert(conerr != INVALID_HANDLE_VALUE);
++    }
++
++    HANDLE childHandle = NULL;
++
++    {
++        // Start the child process under the console.
++        args.childArgv[0] = findProgram(argv[0], args.childArgv[0]);
++        std::string cmdLine = argvToCommandLine(args.childArgv);
++        wchar_t *cmdLineW = heapMbsToWcs(cmdLine.c_str());
++
++        winpty_spawn_config_t *spawnCfg = winpty_spawn_config_new(
++                WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN,
++                NULL, cmdLineW, NULL, NULL, NULL);
++        assert(spawnCfg != NULL);
++
++        winpty_error_ptr_t spawnErr = NULL;
++        DWORD lastError = 0;
++        BOOL spawnRet = winpty_spawn(wp, spawnCfg, &childHandle, NULL,
++            &lastError, &spawnErr);
++        winpty_spawn_config_free(spawnCfg);
++
++        if (!spawnRet) {
++            winpty_result_t spawnCode = winpty_error_code(spawnErr);
++            if (spawnCode == WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED) {
++                fprintf(stderr, "%s: error: cannot start '%s': %s\n",
++                    argv[0],
++                    cmdLine.c_str(),
++                    formatErrorMessage(lastError).c_str());
++            } else {
++                fprintf(stderr, "%s: error: cannot start '%s': internal error: %s\n",
++                    argv[0],
++                    cmdLine.c_str(),
++                    wcsToMbs(winpty_error_msg(spawnErr)).c_str());
++            }
++            exit(1);
++        }
++        winpty_error_free(spawnErr);
++        delete [] cmdLineW;
++    }
++
++    registerResizeSignalHandler();
++    SavedTermiosMode mode =
++        setRawTerminalMode(args.testAllowNonTtys, true, args.testConerr);
++
++    InputHandler inputHandler(conin, STDIN_FILENO, mainWakeup());
++    OutputHandler outputHandler(conout, STDOUT_FILENO, mainWakeup());
++    OutputHandler *errorHandler = NULL;
++    if (args.testConerr) {
++        errorHandler = new OutputHandler(conerr, STDERR_FILENO, mainWakeup());
++    }
++
++    while (true) {
++        fd_set readfds;
++        FD_ZERO(&readfds);
++        FD_SET(mainWakeup().fd(), &readfds);
++        selectWrapper("main thread", mainWakeup().fd() + 1, &readfds);
++        mainWakeup().reset();
++
++        // Check for terminal resize.
++        {
++            winsize sz2;
++            ioctl(STDIN_FILENO, TIOCGWINSZ, &sz2);
++            if (memcmp(&sz, &sz2, sizeof(sz)) != 0) {
++                sz = sz2;
++                winpty_set_size(wp, sz.ws_col, sz.ws_row, NULL);
++            }
++        }
++
++        // Check for an I/O handler shutting down (possibly indicating that the
++        // child process has exited).
++        if (inputHandler.isComplete() || outputHandler.isComplete() ||
++                (errorHandler != NULL && errorHandler->isComplete())) {
++            break;
++        }
++    }
++
++    // Kill the agent connection.  This will kill the agent, closing the CONIN
++    // and CONOUT pipes on the agent pipe, prompting our I/O handler to shut
++    // down.
++    winpty_free(wp);
++
++    inputHandler.shutdown();
++    outputHandler.shutdown();
++    CloseHandle(conin);
++    CloseHandle(conout);
++
++    if (errorHandler != NULL) {
++        errorHandler->shutdown();
++        delete errorHandler;
++        CloseHandle(conerr);
++    }
++
++    restoreTerminalMode(mode);
++
++    DWORD exitCode = 0;
++    if (!GetExitCodeProcess(childHandle, &exitCode)) {
++        exitCode = 1;
++    }
++    CloseHandle(childHandle);
++    return exitCode;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..200193a1b15b7c574a7f59516af2ed8420def78e
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,41 @@@
++# Copyright (c) 2011-2015 Ryan Prichard
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to
++# deal in the Software without restriction, including without limitation the
++# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
++# sell copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
++# IN THE SOFTWARE.
++
++ALL_TARGETS += build/$(UNIX_ADAPTER_EXE)
++
++$(eval $(call def_unix_target,unix-adapter,))
++
++UNIX_ADAPTER_OBJECTS = \
++      build/unix-adapter/unix-adapter/InputHandler.o \
++      build/unix-adapter/unix-adapter/OutputHandler.o \
++      build/unix-adapter/unix-adapter/Util.o \
++      build/unix-adapter/unix-adapter/WakeupFd.o \
++      build/unix-adapter/unix-adapter/main.o \
++      build/unix-adapter/shared/DebugClient.o \
++      build/unix-adapter/shared/WinptyAssert.o \
++      build/unix-adapter/shared/WinptyVersion.o
++
++build/unix-adapter/shared/WinptyVersion.o : build/gen/GenVersion.h
++
++build/$(UNIX_ADAPTER_EXE) : $(UNIX_ADAPTER_OBJECTS) build/winpty.dll
++      $(info Linking $@)
++      @$(UNIX_CXX) $(UNIX_LDFLAGS) -o $@ $^
++
++-include $(UNIX_ADAPTER_OBJECTS:.o=.d)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7ee68d55e6079eecd3e382c604fb0de90b9ef4aa
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,206 @@@
++{
++    # The MSVC generator is the default.  Select the compiler version by
++    # passing -G msvs_version=<ver> to gyp.  <ver> is a string like 2013e.
++    # See gyp\pylib\gyp\MSVSVersion.py for sample version strings.  You
++    # can also pass configurations.gypi to gyp for 32-bit and 64-bit builds.
++    # See that file for details.
++    #
++    # Pass --format=make to gyp to generate a Makefile instead.  The Makefile
++    # can be configured by passing variables to make, e.g.:
++    #    make -j4 CXX=i686-w64-mingw32-g++ LDFLAGS="-static -static-libgcc -static-libstdc++"
++
++    'variables': {
++        'WINPTY_COMMIT_HASH%': '<!(cmd /c "cd shared && GetCommitHash.bat")',
++    },
++    'target_defaults' : {
++        'defines' : [
++            'UNICODE',
++            '_UNICODE',
++            '_WIN32_WINNT=0x0501',
++            'NOMINMAX',
++        ],
++        'include_dirs': [
++            # Add the 'src/gen' directory to the include path and force gyp to
++            # run the script (re)generating the version header.
++            '<!(cmd /c "cd shared && UpdateGenVersion.bat <(WINPTY_COMMIT_HASH)")',
++        ],
++    },
++    'targets' : [
++        {
++            'target_name' : 'winpty-agent',
++            'type' : 'executable',
++            'include_dirs' : [
++                'include',
++            ],
++            'defines' : [
++                'WINPTY_AGENT_ASSERT',
++            ],
++            'libraries' : [
++                '-ladvapi32',
++                '-lshell32',
++                '-luser32',
++            ],
++            'msvs_settings': {
++                # Specify this setting here to override a setting from somewhere
++                # else, such as node's common.gypi.
++                'VCCLCompilerTool': {
++                    'ExceptionHandling': '1', # /EHsc
++                },
++            },
++            'sources' : [
++                'agent/Agent.h',
++                'agent/Agent.cc',
++                'agent/AgentCreateDesktop.h',
++                'agent/AgentCreateDesktop.cc',
++                'agent/ConsoleFont.cc',
++                'agent/ConsoleFont.h',
++                'agent/ConsoleInput.cc',
++                'agent/ConsoleInput.h',
++                'agent/ConsoleInputReencoding.cc',
++                'agent/ConsoleInputReencoding.h',
++                'agent/ConsoleLine.cc',
++                'agent/ConsoleLine.h',
++                'agent/Coord.h',
++                'agent/DebugShowInput.h',
++                'agent/DebugShowInput.cc',
++                'agent/DefaultInputMap.h',
++                'agent/DefaultInputMap.cc',
++                'agent/DsrSender.h',
++                'agent/EventLoop.h',
++                'agent/EventLoop.cc',
++                'agent/InputMap.h',
++                'agent/InputMap.cc',
++                'agent/LargeConsoleRead.h',
++                'agent/LargeConsoleRead.cc',
++                'agent/NamedPipe.h',
++                'agent/NamedPipe.cc',
++                'agent/Scraper.h',
++                'agent/Scraper.cc',
++                'agent/SimplePool.h',
++                'agent/SmallRect.h',
++                'agent/Terminal.h',
++                'agent/Terminal.cc',
++                'agent/UnicodeEncoding.h',
++                'agent/Win32Console.cc',
++                'agent/Win32Console.h',
++                'agent/Win32ConsoleBuffer.cc',
++                'agent/Win32ConsoleBuffer.h',
++                'agent/main.cc',
++                'shared/AgentMsg.h',
++                'shared/BackgroundDesktop.h',
++                'shared/BackgroundDesktop.cc',
++                'shared/Buffer.h',
++                'shared/Buffer.cc',
++                'shared/DebugClient.h',
++                'shared/DebugClient.cc',
++                'shared/GenRandom.h',
++                'shared/GenRandom.cc',
++                'shared/OsModule.h',
++                'shared/OwnedHandle.h',
++                'shared/OwnedHandle.cc',
++                'shared/StringBuilder.h',
++                'shared/StringUtil.cc',
++                'shared/StringUtil.h',
++                'shared/UnixCtrlChars.h',
++                'shared/WindowsSecurity.cc',
++                'shared/WindowsSecurity.h',
++                'shared/WindowsVersion.h',
++                'shared/WindowsVersion.cc',
++                'shared/WinptyAssert.h',
++                'shared/WinptyAssert.cc',
++                'shared/WinptyException.h',
++                'shared/WinptyException.cc',
++                'shared/WinptyVersion.h',
++                'shared/WinptyVersion.cc',
++                'shared/winpty_snprintf.h',
++            ],
++        },
++        {
++            'target_name' : 'winpty',
++            'type' : 'shared_library',
++            'include_dirs' : [
++                'include',
++            ],
++            'defines' : [
++                'COMPILING_WINPTY_DLL',
++            ],
++            'libraries' : [
++                '-ladvapi32',
++                '-luser32',
++            ],
++            'msvs_settings': {
++                # Specify this setting here to override a setting from somewhere
++                # else, such as node's common.gypi.
++                'VCCLCompilerTool': {
++                    'ExceptionHandling': '1', # /EHsc
++                },
++            },
++            'sources' : [
++                'include/winpty.h',
++                'libwinpty/AgentLocation.cc',
++                'libwinpty/AgentLocation.h',
++                'libwinpty/winpty.cc',
++                'shared/AgentMsg.h',
++                'shared/BackgroundDesktop.h',
++                'shared/BackgroundDesktop.cc',
++                'shared/Buffer.h',
++                'shared/Buffer.cc',
++                'shared/DebugClient.h',
++                'shared/DebugClient.cc',
++                'shared/GenRandom.h',
++                'shared/GenRandom.cc',
++                'shared/OsModule.h',
++                'shared/OwnedHandle.h',
++                'shared/OwnedHandle.cc',
++                'shared/StringBuilder.h',
++                'shared/StringUtil.cc',
++                'shared/StringUtil.h',
++                'shared/WindowsSecurity.cc',
++                'shared/WindowsSecurity.h',
++                'shared/WindowsVersion.h',
++                'shared/WindowsVersion.cc',
++                'shared/WinptyAssert.h',
++                'shared/WinptyAssert.cc',
++                'shared/WinptyException.h',
++                'shared/WinptyException.cc',
++                'shared/WinptyVersion.h',
++                'shared/WinptyVersion.cc',
++                'shared/winpty_snprintf.h',
++            ],
++        },
++        {
++            'target_name' : 'winpty-debugserver',
++            'type' : 'executable',
++            'msvs_settings': {
++                # Specify this setting here to override a setting from somewhere
++                # else, such as node's common.gypi.
++                'VCCLCompilerTool': {
++                    'ExceptionHandling': '1', # /EHsc
++                },
++            },
++            'sources' : [
++                'debugserver/DebugServer.cc',
++                'shared/DebugClient.h',
++                'shared/DebugClient.cc',
++                'shared/OwnedHandle.h',
++                'shared/OwnedHandle.cc',
++                'shared/OsModule.h',
++                'shared/StringBuilder.h',
++                'shared/StringUtil.cc',
++                'shared/StringUtil.h',
++                'shared/WindowsSecurity.h',
++                'shared/WindowsSecurity.cc',
++                'shared/WindowsVersion.h',
++                'shared/WindowsVersion.cc',
++                'shared/WinptyAssert.h',
++                'shared/WinptyAssert.cc',
++                'shared/WinptyException.h',
++                'shared/WinptyException.cc',
++                'shared/winpty_snprintf.h',
++            ],
++            'libraries' : [
++                '-ladvapi32',
++            ],
++        }
++    ],
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..f3787a20f13ca2aeb3505787580d88fcc999b317
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,83 @@@
++@echo off
++
++REM -- Script requirements:
++REM --
++REM --  * git               This program must be in the Path to check out
++REM --                      build-gyp.  If that directory already exists, then
++REM --                      git isn't necessary, but if it is missing, no
++REM --                      commit hash will be embedded into binaries.
++REM --
++REM --  * python            A non-Cygwin Python 2 python.exe must be in the
++REM --                      Path to run gyp.
++REM --
++REM --  * msbuild           msbuild must be in the Path.  It is probably
++REM --                      important to have msbuild from the correct MSVC
++REM --                      release.
++REM --
++REM -- The script's output binaries are in the src/Release/{Win32,x64}
++REM -- directory.
++
++REM -------------------------------------------------------------------------
++REM -- Parse arguments
++
++setlocal
++cd %~dp0
++set GYP_ARGS=
++set MSVC_PLATFORM=x64
++
++:ParamLoop
++if "%1" == "" goto :ParamDone
++if "%1" == "--msvc-platform" (
++    REM -- One of Win32 or x64.
++    set MSVC_PLATFORM=%2
++    shift && shift
++    goto :ParamLoop
++)
++if "%1" == "--gyp-msvs-version" (
++    set GYP_ARGS=%GYP_ARGS% -G msvs_version=%2
++    shift && shift
++    goto :ParamLoop
++)
++if "%1" == "--toolset" (
++    set GYP_ARGS=%GYP_ARGS% -D WINPTY_MSBUILD_TOOLSET=%2
++    shift && shift
++    goto :ParamLoop
++)
++if "%1" == "--commit-hash" (
++    set GYP_ARGS=%GYP_ARGS% -D WINPTY_COMMIT_HASH=%2
++    shift && shift
++    goto :ParamLoop
++)
++echo error: Unrecognized argument: %1
++exit /b 1
++:ParamDone
++
++REM -------------------------------------------------------------------------
++REM -- Check out GYP.  GYP doesn't seem to have releases, so just use the
++REM -- current master commit.
++
++if not exist build-gyp (
++    git clone https://chromium.googlesource.com/external/gyp build-gyp || (
++        echo error: GYP clone failed
++        exit /b 1
++    )
++)
++
++REM -------------------------------------------------------------------------
++REM -- Run gyp to generate MSVC project files.
++
++cd src
++
++call ..\build-gyp\gyp.bat winpty.gyp -I configurations.gypi %GYP_ARGS%
++if errorlevel 1 (
++    echo error: GYP failed
++    exit /b 1
++)
++
++REM -------------------------------------------------------------------------
++REM -- Compile the project.
++
++msbuild winpty.sln /m /p:Platform=%MSVC_PLATFORM% || (
++    echo error: msbuild failed
++    exit /b 1
++)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..e5217ef657b54b3c89e3ff55f893f60a53d4db61
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,20 @@@
++"use strict";
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ *
++ * This module fetches the console process list for a particular PID. It must be
++ * called from a different process (child_process.fork) as there can only be a
++ * single console attached to a process.
++ */
++var getConsoleProcessList;
++try {
++    getConsoleProcessList = require('../build/Release/conpty_console_list.node').getConsoleProcessList;
++}
++catch (err) {
++    getConsoleProcessList = require('../build/Debug/conpty_console_list.node').getConsoleProcessList;
++}
++var shellPid = parseInt(process.argv[2], 10);
++var consoleProcessList = getConsoleProcessList(shellPid);
++process.send({ consoleProcessList: consoleProcessList });
++process.exit(0);
++//# sourceMappingURL=conpty_console_list_agent.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7d0ad0893e88cdd05c1d03a371df690dbbbaa4f6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"conpty_console_list_agent.js","sourceRoot":"","sources":["../src/conpty_console_list_agent.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;AAEH,IAAI,qBAA0B,CAAC;AAC/B,IAAI;IACF,qBAAqB,GAAG,OAAO,CAAC,2CAA2C,CAAC,CAAC,qBAAqB,CAAC;CACpG;AAAC,OAAO,GAAG,EAAE;IACZ,qBAAqB,GAAG,OAAO,CAAC,yCAAyC,CAAC,CAAC,qBAAqB,CAAC;CAClG;AAED,IAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/C,IAAM,kBAAkB,GAAG,qBAAqB,CAAC,QAAQ,CAAC,CAAC;AAC3D,OAAO,CAAC,IAAI,CAAC,EAAE,kBAAkB,oBAAA,EAAE,CAAC,CAAC;AACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c53d1f0bcbf1e49b48f000fab480c4e7e7d5e4b5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,46 @@@
++"use strict";
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var EventEmitter2 = /** @class */ (function () {
++    function EventEmitter2() {
++        this._listeners = [];
++    }
++    Object.defineProperty(EventEmitter2.prototype, "event", {
++        get: function () {
++            var _this = this;
++            if (!this._event) {
++                this._event = function (listener) {
++                    _this._listeners.push(listener);
++                    var disposable = {
++                        dispose: function () {
++                            for (var i = 0; i < _this._listeners.length; i++) {
++                                if (_this._listeners[i] === listener) {
++                                    _this._listeners.splice(i, 1);
++                                    return;
++                                }
++                            }
++                        }
++                    };
++                    return disposable;
++                };
++            }
++            return this._event;
++        },
++        enumerable: true,
++        configurable: true
++    });
++    EventEmitter2.prototype.fire = function (data) {
++        var queue = [];
++        for (var i = 0; i < this._listeners.length; i++) {
++            queue.push(this._listeners[i]);
++        }
++        for (var i = 0; i < queue.length; i++) {
++            queue[i].call(undefined, data);
++        }
++    };
++    return EventEmitter2;
++}());
++exports.EventEmitter2 = EventEmitter2;
++//# sourceMappingURL=eventEmitter2.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b850094c46dc0740857a0509b627eaefd4db5e40
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"eventEmitter2.js","sourceRoot":"","sources":["../src/eventEmitter2.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAYH;IAAA;QACU,eAAU,GAAmB,EAAE,CAAC;IAgC1C,CAAC;IA7BC,sBAAW,gCAAK;aAAhB;YAAA,iBAkBC;YAjBC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;gBAChB,IAAI,CAAC,MAAM,GAAG,UAAC,QAAuB;oBACpC,KAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;oBAC/B,IAAM,UAAU,GAAG;wBACjB,OAAO,EAAE;4BACP,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gCAC/C,IAAI,KAAI,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;oCACnC,KAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;oCAC7B,OAAO;iCACR;6BACF;wBACH,CAAC;qBACF,CAAC;oBACF,OAAO,UAAU,CAAC;gBACpB,CAAC,CAAC;aACH;YACD,OAAO,IAAI,CAAC,MAAM,CAAC;QACrB,CAAC;;;OAAA;IAEM,4BAAI,GAAX,UAAY,IAAO;QACjB,IAAM,KAAK,GAAmB,EAAE,CAAC;QACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC/C,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;SAChC;QACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACrC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;SAChC;IACH,CAAC;IACH,oBAAC;AAAD,CAAC,AAjCD,IAiCC;AAjCY,sCAAa"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..14e65a0b126f04d1881e7926e77fd9515b8ebf4b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,30 @@@
++"use strict";
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var assert = require("assert");
++var eventEmitter2_1 = require("./eventEmitter2");
++describe('EventEmitter2', function () {
++    it('should fire listeners multiple times', function () {
++        var order = [];
++        var emitter = new eventEmitter2_1.EventEmitter2();
++        emitter.event(function (data) { return order.push(data + 'a'); });
++        emitter.event(function (data) { return order.push(data + 'b'); });
++        emitter.fire(1);
++        emitter.fire(2);
++        assert.deepEqual(order, ['1a', '1b', '2a', '2b']);
++    });
++    it('should not fire listeners once disposed', function () {
++        var order = [];
++        var emitter = new eventEmitter2_1.EventEmitter2();
++        emitter.event(function (data) { return order.push(data + 'a'); });
++        var disposeB = emitter.event(function (data) { return order.push(data + 'b'); });
++        emitter.event(function (data) { return order.push(data + 'c'); });
++        emitter.fire(1);
++        disposeB.dispose();
++        emitter.fire(2);
++        assert.deepEqual(order, ['1a', '1b', '1c', '2a', '2c']);
++    });
++});
++//# sourceMappingURL=eventEmitter2.test.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d3b95e6b7713e4b603bedfb5dfd6f4fe58264c49
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"eventEmitter2.test.js","sourceRoot":"","sources":["../src/eventEmitter2.test.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,+BAAiC;AACjC,iDAAgD;AAEhD,QAAQ,CAAC,eAAe,EAAE;IACxB,EAAE,CAAC,sCAAsC,EAAE;QACzC,IAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,IAAM,OAAO,GAAG,IAAI,6BAAa,EAAU,CAAC;QAC5C,OAAO,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,EAAtB,CAAsB,CAAC,CAAC;QAC9C,OAAO,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,EAAtB,CAAsB,CAAC,CAAC;QAC9C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChB,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,CAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAE,CAAC,CAAC;IACtD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,yCAAyC,EAAE;QAC5C,IAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,IAAM,OAAO,GAAG,IAAI,6BAAa,EAAU,CAAC;QAC5C,OAAO,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,EAAtB,CAAsB,CAAC,CAAC;QAC9C,IAAM,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,EAAtB,CAAsB,CAAC,CAAC;QAC/D,OAAO,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,EAAtB,CAAsB,CAAC,CAAC;QAC9C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChB,QAAQ,CAAC,OAAO,EAAE,CAAC;QACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChB,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,CAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAE,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..904748e9dd476b670a0927acaa3c973b0389b085
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,50 @@@
++"use strict";
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var terminalCtor;
++if (process.platform === 'win32') {
++    terminalCtor = require('./windowsTerminal').WindowsTerminal;
++}
++else {
++    terminalCtor = require('./unixTerminal').UnixTerminal;
++}
++/**
++ * Forks a process as a pseudoterminal.
++ * @param file The file to launch.
++ * @param args The file's arguments as argv (string[]) or in a pre-escaped
++ * CommandLine format (string). Note that the CommandLine option is only
++ * available on Windows and is expected to be escaped properly.
++ * @param options The options of the terminal.
++ * @throws When the file passed to spawn with does not exists.
++ * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
++ * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
++ * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx
++ */
++function spawn(file, args, opt) {
++    return new terminalCtor(file, args, opt);
++}
++exports.spawn = spawn;
++/** @deprecated */
++function fork(file, args, opt) {
++    return new terminalCtor(file, args, opt);
++}
++exports.fork = fork;
++/** @deprecated */
++function createTerminal(file, args, opt) {
++    return new terminalCtor(file, args, opt);
++}
++exports.createTerminal = createTerminal;
++function open(options) {
++    return terminalCtor.open(options);
++}
++exports.open = open;
++/**
++ * Expose the native API when not Windows, note that this is not public API and
++ * could be removed at any time.
++ */
++exports.native = (process.platform !== 'win32' ? require('../build/Release/pty.node') : null);
++//# sourceMappingURL=index.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..74162a6460cccbe7616b8a1aebd6ce662a7ce668
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAKH,IAAI,YAAiB,CAAC;AACtB,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,YAAY,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC,eAAe,CAAC;CAC7D;KAAM;IACL,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC,YAAY,CAAC;CACvD;AAED;;;;;;;;;;;GAWG;AACH,SAAgB,KAAK,CAAC,IAAa,EAAE,IAAwB,EAAE,GAA8C;IAC3G,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC;AAFD,sBAEC;AAED,kBAAkB;AAClB,SAAgB,IAAI,CAAC,IAAa,EAAE,IAAwB,EAAE,GAA8C;IAC1G,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC;AAFD,oBAEC;AAED,kBAAkB;AAClB,SAAgB,cAAc,CAAC,IAAa,EAAE,IAAwB,EAAE,GAA8C;IACpH,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC;AAFD,wCAEC;AAED,SAAgB,IAAI,CAAC,OAAwB;IAC3C,OAAO,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC;AAFD,oBAEC;AAED;;;GAGG;AACU,QAAA,MAAM,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..63c5d5b8bd7db30666538339a2425b2dd0d973b9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,7 @@@
++"use strict";
++/**
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++//# sourceMappingURL=interfaces.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ab6d3812bf264ded525527254e1158180238870b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":";AAAA;;;GAGG"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a4f1eedc35006869923113cc862fea7a6c58a255
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,167 @@@
++"use strict";
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var events_1 = require("events");
++var eventEmitter2_1 = require("./eventEmitter2");
++exports.DEFAULT_COLS = 80;
++exports.DEFAULT_ROWS = 24;
++/**
++ * Default messages to indicate PAUSE/RESUME for automatic flow control.
++ * To avoid conflicts with rebound XON/XOFF control codes (such as on-my-zsh),
++ * the sequences can be customized in `IPtyForkOptions`.
++ */
++var FLOW_CONTROL_PAUSE = '\x13'; // defaults to XOFF
++var FLOW_CONTROL_RESUME = '\x11'; // defaults to XON
++var Terminal = /** @class */ (function () {
++    function Terminal(opt) {
++        this._onData = new eventEmitter2_1.EventEmitter2();
++        this._onExit = new eventEmitter2_1.EventEmitter2();
++        // for 'close'
++        this._internalee = new events_1.EventEmitter();
++        if (!opt) {
++            return;
++        }
++        // Do basic type checks here in case node-pty is being used within JavaScript. If the wrong
++        // types go through to the C++ side it can lead to hard to diagnose exceptions.
++        this._checkType('name', opt.name ? opt.name : null, 'string');
++        this._checkType('cols', opt.cols ? opt.cols : null, 'number');
++        this._checkType('rows', opt.rows ? opt.rows : null, 'number');
++        this._checkType('cwd', opt.cwd ? opt.cwd : null, 'string');
++        this._checkType('env', opt.env ? opt.env : null, 'object');
++        this._checkType('uid', opt.uid ? opt.uid : null, 'number');
++        this._checkType('gid', opt.gid ? opt.gid : null, 'number');
++        this._checkType('encoding', opt.encoding ? opt.encoding : null, 'string');
++        // setup flow control handling
++        this.handleFlowControl = !!(opt.handleFlowControl);
++        this._flowControlPause = opt.flowControlPause || FLOW_CONTROL_PAUSE;
++        this._flowControlResume = opt.flowControlResume || FLOW_CONTROL_RESUME;
++    }
++    Object.defineProperty(Terminal.prototype, "onData", {
++        get: function () { return this._onData.event; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(Terminal.prototype, "onExit", {
++        get: function () { return this._onExit.event; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(Terminal.prototype, "pid", {
++        get: function () { return this._pid; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(Terminal.prototype, "cols", {
++        get: function () { return this._cols; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(Terminal.prototype, "rows", {
++        get: function () { return this._rows; },
++        enumerable: true,
++        configurable: true
++    });
++    Terminal.prototype.write = function (data) {
++        if (this.handleFlowControl) {
++            // PAUSE/RESUME messages are not forwarded to the pty
++            if (data === this._flowControlPause) {
++                this.pause();
++                return;
++            }
++            if (data === this._flowControlResume) {
++                this.resume();
++                return;
++            }
++        }
++        // everything else goes to the real pty
++        this._write(data);
++    };
++    Terminal.prototype._forwardEvents = function () {
++        var _this = this;
++        this.on('data', function (e) { return _this._onData.fire(e); });
++        this.on('exit', function (exitCode, signal) { return _this._onExit.fire({ exitCode: exitCode, signal: signal }); });
++    };
++    Terminal.prototype._checkType = function (name, value, type) {
++        if (value && typeof value !== type) {
++            throw new Error(name + " must be a " + type + " (not a " + typeof value + ")");
++        }
++    };
++    /** See net.Socket.end */
++    Terminal.prototype.end = function (data) {
++        this._socket.end(data);
++    };
++    /** See stream.Readable.pipe */
++    Terminal.prototype.pipe = function (dest, options) {
++        return this._socket.pipe(dest, options);
++    };
++    /** See net.Socket.pause */
++    Terminal.prototype.pause = function () {
++        return this._socket.pause();
++    };
++    /** See net.Socket.resume */
++    Terminal.prototype.resume = function () {
++        return this._socket.resume();
++    };
++    /** See net.Socket.setEncoding */
++    Terminal.prototype.setEncoding = function (encoding) {
++        if (this._socket._decoder) {
++            delete this._socket._decoder;
++        }
++        if (encoding) {
++            this._socket.setEncoding(encoding);
++        }
++    };
++    Terminal.prototype.addListener = function (eventName, listener) { this.on(eventName, listener); };
++    Terminal.prototype.on = function (eventName, listener) {
++        if (eventName === 'close') {
++            this._internalee.on('close', listener);
++            return;
++        }
++        this._socket.on(eventName, listener);
++    };
++    Terminal.prototype.emit = function (eventName) {
++        var args = [];
++        for (var _i = 1; _i < arguments.length; _i++) {
++            args[_i - 1] = arguments[_i];
++        }
++        if (eventName === 'close') {
++            return this._internalee.emit.apply(this._internalee, arguments);
++        }
++        return this._socket.emit.apply(this._socket, arguments);
++    };
++    Terminal.prototype.listeners = function (eventName) {
++        return this._socket.listeners(eventName);
++    };
++    Terminal.prototype.removeListener = function (eventName, listener) {
++        this._socket.removeListener(eventName, listener);
++    };
++    Terminal.prototype.removeAllListeners = function (eventName) {
++        this._socket.removeAllListeners(eventName);
++    };
++    Terminal.prototype.once = function (eventName, listener) {
++        this._socket.once(eventName, listener);
++    };
++    Terminal.prototype._close = function () {
++        this._socket.writable = false;
++        this._socket.readable = false;
++        this.write = function () { };
++        this.end = function () { };
++        this._writable = false;
++        this._readable = false;
++    };
++    Terminal.prototype._parseEnv = function (env) {
++        var keys = Object.keys(env || {});
++        var pairs = [];
++        for (var i = 0; i < keys.length; i++) {
++            pairs.push(keys[i] + '=' + env[keys[i]]);
++        }
++        return pairs;
++    };
++    return Terminal;
++}());
++exports.Terminal = Terminal;
++//# sourceMappingURL=terminal.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..5fe6aaa3ac2ccf446d7f48a0acfdb88acd5defa9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"terminal.js","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAGH,iCAAsC;AAEtC,iDAAwD;AAG3C,QAAA,YAAY,GAAW,EAAE,CAAC;AAC1B,QAAA,YAAY,GAAW,EAAE,CAAC;AAEvC;;;;GAIG;AACH,IAAM,kBAAkB,GAAI,MAAM,CAAC,CAAG,mBAAmB;AACzD,IAAM,mBAAmB,GAAG,MAAM,CAAC,CAAG,kBAAkB;AAExD;IA4BE,kBAAY,GAAqB;QATzB,YAAO,GAAG,IAAI,6BAAa,EAAU,CAAC;QAEtC,YAAO,GAAG,IAAI,6BAAa,EAAc,CAAC;QAQhD,cAAc;QACd,IAAI,CAAC,WAAW,GAAG,IAAI,qBAAY,EAAE,CAAC;QAEtC,IAAI,CAAC,GAAG,EAAE;YACR,OAAO;SACR;QAED,2FAA2F;QAC3F,+EAA+E;QAC/E,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC9D,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC9D,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC9D,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC3D,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC3D,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC3D,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC3D,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAE1E,8BAA8B;QAC9B,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QACnD,IAAI,CAAC,iBAAiB,GAAG,GAAG,CAAC,gBAAgB,IAAI,kBAAkB,CAAC;QACpE,IAAI,CAAC,kBAAkB,GAAG,GAAG,CAAC,iBAAiB,IAAI,mBAAmB,CAAC;IACzE,CAAC;IA/BD,sBAAW,4BAAM;aAAjB,cAAsC,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;;;OAAA;IAElE,sBAAW,4BAAM;aAAjB,cAA0C,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;;;OAAA;IAEtE,sBAAW,yBAAG;aAAd,cAA2B,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;;;OAAA;IAC9C,sBAAW,0BAAI;aAAf,cAA4B,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;;;OAAA;IAChD,sBAAW,0BAAI;aAAf,cAA4B,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;;;OAAA;IA6BzC,wBAAK,GAAZ,UAAa,IAAY;QACvB,IAAI,IAAI,CAAC,iBAAiB,EAAE;YAC1B,qDAAqD;YACrD,IAAI,IAAI,KAAK,IAAI,CAAC,iBAAiB,EAAE;gBACnC,IAAI,CAAC,KAAK,EAAE,CAAC;gBACb,OAAO;aACR;YACD,IAAI,IAAI,KAAK,IAAI,CAAC,kBAAkB,EAAE;gBACpC,IAAI,CAAC,MAAM,EAAE,CAAC;gBACd,OAAO;aACR;SACF;QACD,uCAAuC;QACvC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAES,iCAAc,GAAxB;QAAA,iBAGC;QAFC,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAA,CAAC,IAAI,OAAA,KAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAApB,CAAoB,CAAC,CAAC;QAC3C,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,QAAQ,EAAE,MAAM,IAAK,OAAA,KAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,UAAA,EAAE,MAAM,QAAA,EAAE,CAAC,EAAvC,CAAuC,CAAC,CAAC;IACjF,CAAC;IAEO,6BAAU,GAAlB,UAAmB,IAAY,EAAE,KAAU,EAAE,IAAY;QACvD,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,EAAE;YAClC,MAAM,IAAI,KAAK,CAAI,IAAI,mBAAc,IAAI,gBAAW,OAAO,KAAK,MAAG,CAAC,CAAC;SACtE;IACH,CAAC;IAED,yBAAyB;IAClB,sBAAG,GAAV,UAAW,IAAY;QACrB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC;IAED,+BAA+B;IACxB,uBAAI,GAAX,UAAY,IAAS,EAAE,OAAY;QACjC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC1C,CAAC;IAED,2BAA2B;IACpB,wBAAK,GAAZ;QACE,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,4BAA4B;IACrB,yBAAM,GAAb;QACE,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;IAC/B,CAAC;IAED,iCAAiC;IAC1B,8BAAW,GAAlB,UAAmB,QAAuB;QACxC,IAAU,IAAI,CAAC,OAAQ,CAAC,QAAQ,EAAE;YAChC,OAAa,IAAI,CAAC,OAAQ,CAAC,QAAQ,CAAC;SACrC;QACD,IAAI,QAAQ,EAAE;YACZ,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SACpC;IACH,CAAC;IAEM,8BAAW,GAAlB,UAAmB,SAAiB,EAAE,QAAiC,IAAU,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IACzG,qBAAE,GAAT,UAAU,SAAiB,EAAE,QAAiC;QAC5D,IAAI,SAAS,KAAK,OAAO,EAAE;YACzB,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACvC,OAAO;SACR;QACD,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACvC,CAAC;IAEM,uBAAI,GAAX,UAAY,SAAiB;QAAE,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,6BAAc;;QAC3C,IAAI,SAAS,KAAK,OAAO,EAAE;YACzB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;SACjE;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC;IAEM,4BAAS,GAAhB,UAAiB,SAAiB;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC3C,CAAC;IAEM,iCAAc,GAArB,UAAsB,SAAiB,EAAE,QAAiC;QACxE,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACnD,CAAC;IAEM,qCAAkB,GAAzB,UAA0B,SAAiB;QACzC,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;IAC7C,CAAC;IAEM,uBAAI,GAAX,UAAY,SAAiB,EAAE,QAAiC;QAC9D,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;IAUS,yBAAM,GAAhB;QACE,IAAI,CAAC,OAAO,CAAC,QAAQ,GAAG,KAAK,CAAC;QAC9B,IAAI,CAAC,OAAO,CAAC,QAAQ,GAAG,KAAK,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,cAAO,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,GAAG,cAAO,CAAC,CAAC;QACpB,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;IAES,4BAAS,GAAnB,UAAoB,GAA4B;QAC9C,IAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;QACpC,IAAM,KAAK,GAAG,EAAE,CAAC;QAEjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAC1C;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IACH,eAAC;AAAD,CAAC,AA3KD,IA2KC;AA3KqB,4BAAQ"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..da0e516d0caeacbd3802a634bf1ec4f352104b7b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,58 @@@
++"use strict";
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var assert = require("assert");
++var windowsTerminal_1 = require("./windowsTerminal");
++var unixTerminal_1 = require("./unixTerminal");
++var terminalConstructor = (process.platform === 'win32') ? windowsTerminal_1.WindowsTerminal : unixTerminal_1.UnixTerminal;
++var SHELL = (process.platform === 'win32') ? 'cmd.exe' : '/bin/bash';
++var terminalCtor;
++if (process.platform === 'win32') {
++    terminalCtor = require('./windowsTerminal');
++}
++else {
++    terminalCtor = require('./unixTerminal');
++}
++describe('Terminal', function () {
++    describe('constructor', function () {
++        it('should do basic type checks', function () {
++            assert.throws(function () { return new terminalCtor('a', 'b', { 'name': {} }); }, 'name must be a string (not a object)');
++        });
++    });
++    describe('automatic flow control', function () {
++        it('should respect ctor flow control options', function () {
++            var pty = new terminalConstructor(SHELL, [], { handleFlowControl: true, flowControlPause: 'abc', flowControlResume: '123' });
++            assert.equal(pty.handleFlowControl, true);
++            assert.equal(pty._flowControlPause, 'abc');
++            assert.equal(pty._flowControlResume, '123');
++        });
++        // TODO: I don't think this test ever worked due to pollUntil being used incorrectly
++        // it('should do flow control automatically', async function(): Promise<void> {
++        //   // Flow control doesn't work on Windows
++        //   if (process.platform === 'win32') {
++        //     return;
++        //   }
++        //   this.timeout(10000);
++        //   const pty = new terminalConstructor(SHELL, [], {handleFlowControl: true, flowControlPause: 'PAUSE', flowControlResume: 'RESUME'});
++        //   let read: string = '';
++        //   pty.on('data', data => read += data);
++        //   pty.on('pause', () => read += 'paused');
++        //   pty.on('resume', () => read += 'resumed');
++        //   pty.write('1');
++        //   pty.write('PAUSE');
++        //   pty.write('2');
++        //   pty.write('RESUME');
++        //   pty.write('3');
++        //   await pollUntil(() => {
++        //     return stripEscapeSequences(read).endsWith('1pausedresumed23');
++        //   }, 100, 10);
++        // });
++    });
++});
++function stripEscapeSequences(data) {
++    return data.replace(/\u001b\[0K/, '');
++}
++//# sourceMappingURL=terminal.test.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8f25cd6c9e963fd856d579ea2d03116ec30e24c5
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"terminal.test.js","sourceRoot":"","sources":["../src/terminal.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,+BAAiC;AACjC,qDAAoD;AACpD,+CAA8C;AAG9C,IAAM,mBAAmB,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,iCAAe,CAAC,CAAC,CAAC,2BAAY,CAAC;AAC5F,IAAM,KAAK,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;AAEvE,IAAI,YAA4C,CAAC;AACjD,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,YAAY,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC7C;KAAM;IACL,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC1C;AAGD,QAAQ,CAAC,UAAU,EAAE;IACnB,QAAQ,CAAC,aAAa,EAAE;QACtB,EAAE,CAAC,6BAA6B,EAAE;YAChC,MAAM,CAAC,MAAM,CACX,cAAM,OAAA,IAAU,YAAa,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,EAAjD,CAAiD,EACvD,sCAAsC,CACvC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,wBAAwB,EAAE;QACjC,EAAE,CAAC,0CAA0C,EAAE;YAC7C,IAAM,GAAG,GAAG,IAAI,mBAAmB,CAAC,KAAK,EAAE,EAAE,EAAE,EAAC,iBAAiB,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,iBAAiB,EAAE,KAAK,EAAC,CAAC,CAAC;YAC7H,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;YAC1C,MAAM,CAAC,KAAK,CAAE,GAAW,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;YACpD,MAAM,CAAC,KAAK,CAAE,GAAW,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;QACH,oFAAoF;QACpF,+EAA+E;QAC/E,4CAA4C;QAC5C,wCAAwC;QACxC,cAAc;QACd,MAAM;QAEN,yBAAyB;QACzB,uIAAuI;QACvI,2BAA2B;QAC3B,0CAA0C;QAC1C,6CAA6C;QAC7C,+CAA+C;QAC/C,oBAAoB;QACpB,wBAAwB;QACxB,oBAAoB;QACpB,yBAAyB;QACzB,oBAAoB;QACpB,4BAA4B;QAC5B,sEAAsE;QACtE,iBAAiB;QACjB,MAAM;IACR,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAS,oBAAoB,CAAC,IAAY;IACxC,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;AACxC,CAAC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b861d367a68452072befaed4fd18215db55683e8
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,27 @@@
++"use strict";
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++function pollUntil(cb, timeout, interval) {
++    return new Promise(function (resolve, reject) {
++        var intervalId = setInterval(function () {
++            if (cb()) {
++                clearInterval(intervalId);
++                clearTimeout(timeoutId);
++                resolve();
++            }
++        }, interval);
++        var timeoutId = setTimeout(function () {
++            clearInterval(intervalId);
++            if (cb()) {
++                resolve();
++            }
++            else {
++                reject();
++            }
++        }, timeout);
++    });
++}
++exports.pollUntil = pollUntil;
++//# sourceMappingURL=testUtils.test.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..73b16dcae45a5ef50f5a98049310e6b350931ae4
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"testUtils.test.js","sourceRoot":"","sources":["../src/testUtils.test.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,SAAgB,SAAS,CAAC,EAAiB,EAAE,OAAe,EAAE,QAAgB;IAC5E,OAAO,IAAI,OAAO,CAAO,UAAC,OAAO,EAAE,MAAM;QACvC,IAAM,UAAU,GAAG,WAAW,CAAC;YAC7B,IAAI,EAAE,EAAE,EAAE;gBACR,aAAa,CAAC,UAAU,CAAC,CAAC;gBAC1B,YAAY,CAAC,SAAS,CAAC,CAAC;gBACxB,OAAO,EAAE,CAAC;aACX;QACH,CAAC,EAAE,QAAQ,CAAC,CAAC;QACb,IAAM,SAAS,GAAG,UAAU,CAAC;YAC3B,aAAa,CAAC,UAAU,CAAC,CAAC;YAC1B,IAAI,EAAE,EAAE,EAAE;gBACR,OAAO,EAAE,CAAC;aACX;iBAAM;gBACL,MAAM,EAAE,CAAC;aACV;QACH,CAAC,EAAE,OAAO,CAAC,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAlBD,8BAkBC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3768e95f67f19cf7e176728d8add1c1c4f53e839
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,7 @@@
++"use strict";
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++//# sourceMappingURL=types.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..5ab8a9573c095c9cc70a09d88b7a8b95255b0253
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA;;;GAGG"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..004364d19eeb2d745dcda26a6b44db25d79bc952
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,276 @@@
++"use strict";
++var __extends = (this && this.__extends) || (function () {
++    var extendStatics = function (d, b) {
++        extendStatics = Object.setPrototypeOf ||
++            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
++            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
++        return extendStatics(d, b);
++    };
++    return function (d, b) {
++        extendStatics(d, b);
++        function __() { this.constructor = d; }
++        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
++    };
++})();
++Object.defineProperty(exports, "__esModule", { value: true });
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++var net = require("net");
++var terminal_1 = require("./terminal");
++var utils_1 = require("./utils");
++var pty;
++try {
++    pty = require('../build/Release/pty.node');
++}
++catch (outerError) {
++    try {
++        pty = require('../build/Debug/pty.node');
++    }
++    catch (innerError) {
++        console.error('innerError', innerError);
++        // Re-throw the exception from the Release require if the Debug require fails as well
++        throw outerError;
++    }
++}
++var DEFAULT_FILE = 'sh';
++var DEFAULT_NAME = 'xterm';
++var DESTROY_SOCKET_TIMEOUT_MS = 200;
++var UnixTerminal = /** @class */ (function (_super) {
++    __extends(UnixTerminal, _super);
++    function UnixTerminal(file, args, opt) {
++        var _this = _super.call(this, opt) || this;
++        if (typeof args === 'string') {
++            throw new Error('args as a string is not supported on unix.');
++        }
++        // Initialize arguments
++        args = args || [];
++        file = file || DEFAULT_FILE;
++        opt = opt || {};
++        opt.env = opt.env || process.env;
++        _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
++        _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
++        var uid = opt.uid || -1;
++        var gid = opt.gid || -1;
++        var env = utils_1.assign({}, opt.env);
++        if (opt.env === process.env) {
++            _this._sanitizeEnv(env);
++        }
++        var cwd = opt.cwd || process.cwd();
++        var name = opt.name || env.TERM || DEFAULT_NAME;
++        env.TERM = name;
++        var parsedEnv = _this._parseEnv(env);
++        var encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
++        var onexit = function (code, signal) {
++            // XXX Sometimes a data event is emitted after exit. Wait til socket is
++            // destroyed.
++            if (!_this._emittedClose) {
++                if (_this._boundClose) {
++                    return;
++                }
++                _this._boundClose = true;
++                // From macOS High Sierra 10.13.2 sometimes the socket never gets
++                // closed. A timeout is applied here to avoid the terminal never being
++                // destroyed when this occurs.
++                var timeout_1 = setTimeout(function () {
++                    timeout_1 = null;
++                    // Destroying the socket now will cause the close event to fire
++                    _this._socket.destroy();
++                }, DESTROY_SOCKET_TIMEOUT_MS);
++                _this.once('close', function () {
++                    if (timeout_1 !== null) {
++                        clearTimeout(timeout_1);
++                    }
++                    _this.emit('exit', code, signal);
++                });
++                return;
++            }
++            _this.emit('exit', code, signal);
++        };
++        // fork
++        var term = pty.fork(file, args, parsedEnv, cwd, _this._cols, _this._rows, uid, gid, (encoding === 'utf8'), onexit);
++        _this._socket = new PipeSocket(term.fd);
++        if (encoding !== null) {
++            _this._socket.setEncoding(encoding);
++        }
++        // setup
++        _this._socket.on('error', function (err) {
++            // NOTE: fs.ReadStream gets EAGAIN twice at first:
++            if (err.code) {
++                if (~err.code.indexOf('EAGAIN')) {
++                    return;
++                }
++            }
++            // close
++            _this._close();
++            // EIO on exit from fs.ReadStream:
++            if (!_this._emittedClose) {
++                _this._emittedClose = true;
++                _this.emit('close');
++            }
++            // EIO, happens when someone closes our child process: the only process in
++            // the terminal.
++            // node < 0.6.14: errno 5
++            // node >= 0.6.14: read EIO
++            if (err.code) {
++                if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) {
++                    return;
++                }
++            }
++            // throw anything else
++            if (_this.listeners('error').length < 2) {
++                throw err;
++            }
++        });
++        _this._pid = term.pid;
++        _this._fd = term.fd;
++        _this._pty = term.pty;
++        _this._file = file;
++        _this._name = name;
++        _this._readable = true;
++        _this._writable = true;
++        _this._socket.on('close', function () {
++            if (_this._emittedClose) {
++                return;
++            }
++            _this._emittedClose = true;
++            _this._close();
++            _this.emit('close');
++        });
++        _this._forwardEvents();
++        return _this;
++    }
++    Object.defineProperty(UnixTerminal.prototype, "master", {
++        get: function () { return this._master; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(UnixTerminal.prototype, "slave", {
++        get: function () { return this._slave; },
++        enumerable: true,
++        configurable: true
++    });
++    UnixTerminal.prototype._write = function (data) {
++        this._socket.write(data);
++    };
++    /**
++     * openpty
++     */
++    UnixTerminal.open = function (opt) {
++        var self = Object.create(UnixTerminal.prototype);
++        opt = opt || {};
++        if (arguments.length > 1) {
++            opt = {
++                cols: arguments[1],
++                rows: arguments[2]
++            };
++        }
++        var cols = opt.cols || terminal_1.DEFAULT_COLS;
++        var rows = opt.rows || terminal_1.DEFAULT_ROWS;
++        var encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
++        // open
++        var term = pty.open(cols, rows);
++        self._master = new PipeSocket(term.master);
++        if (encoding !== null) {
++            self._master.setEncoding(encoding);
++        }
++        self._master.resume();
++        self._slave = new PipeSocket(term.slave);
++        if (encoding !== null) {
++            self._slave.setEncoding(encoding);
++        }
++        self._slave.resume();
++        self._socket = self._master;
++        self._pid = null;
++        self._fd = term.master;
++        self._pty = term.pty;
++        self._file = process.argv[0] || 'node';
++        self._name = process.env.TERM || '';
++        self._readable = true;
++        self._writable = true;
++        self._socket.on('error', function (err) {
++            self._close();
++            if (self.listeners('error').length < 2) {
++                throw err;
++            }
++        });
++        self._socket.on('close', function () {
++            self._close();
++        });
++        return self;
++    };
++    UnixTerminal.prototype.destroy = function () {
++        var _this = this;
++        this._close();
++        // Need to close the read stream so node stops reading a dead file
++        // descriptor. Then we can safely SIGHUP the shell.
++        this._socket.once('close', function () {
++            _this.kill('SIGHUP');
++        });
++        this._socket.destroy();
++    };
++    UnixTerminal.prototype.kill = function (signal) {
++        try {
++            process.kill(this.pid, signal || 'SIGHUP');
++        }
++        catch (e) { /* swallow */ }
++    };
++    Object.defineProperty(UnixTerminal.prototype, "process", {
++        /**
++         * Gets the name of the process.
++         */
++        get: function () {
++            return pty.process(this._fd, this._pty) || this._file;
++        },
++        enumerable: true,
++        configurable: true
++    });
++    /**
++     * TTY
++     */
++    UnixTerminal.prototype.resize = function (cols, rows) {
++        if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
++            throw new Error('resizing must be done using positive cols and rows');
++        }
++        pty.resize(this._fd, cols, rows);
++        this._cols = cols;
++        this._rows = rows;
++    };
++    UnixTerminal.prototype._sanitizeEnv = function (env) {
++        // Make sure we didn't start our server from inside tmux.
++        delete env['TMUX'];
++        delete env['TMUX_PANE'];
++        // Make sure we didn't start our server from inside screen.
++        // http://web.mit.edu/gnu/doc/html/screen_20.html
++        delete env['STY'];
++        delete env['WINDOW'];
++        // Delete some variables that might confuse our terminal.
++        delete env['WINDOWID'];
++        delete env['TERMCAP'];
++        delete env['COLUMNS'];
++        delete env['LINES'];
++    };
++    return UnixTerminal;
++}(terminal_1.Terminal));
++exports.UnixTerminal = UnixTerminal;
++/**
++ * Wraps net.Socket to force the handle type "PIPE" by temporarily overwriting
++ * tty_wrap.guessHandleType.
++ * See: https://github.com/chjj/pty.js/issues/103
++ */
++var PipeSocket = /** @class */ (function (_super) {
++    __extends(PipeSocket, _super);
++    function PipeSocket(fd) {
++        var _this = this;
++        var _a = process.binding('pipe_wrap'), Pipe = _a.Pipe, constants = _a.constants; // tslint:disable-line
++        // @types/node has fd as string? https://github.com/DefinitelyTyped/DefinitelyTyped/pull/18275
++        var handle = new Pipe(constants.SOCKET);
++        handle.open(fd);
++        _this = _super.call(this, { handle: handle }) || this;
++        return _this;
++    }
++    return PipeSocket;
++}(net.Socket));
++//# sourceMappingURL=unixTerminal.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3275877b5a431d348edfb8fce8c0ad7813c3e5af
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"unixTerminal.js","sourceRoot":"","sources":["../src/unixTerminal.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA;;;;GAIG;AACH,yBAA2B;AAC3B,uCAAkE;AAGlE,iCAAiC;AAEjC,IAAI,GAAgB,CAAC;AACrB,IAAI;IACF,GAAG,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;CAC5C;AAAC,OAAO,UAAU,EAAE;IACnB,IAAI;QACF,GAAG,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;KAC1C;IAAC,OAAO,UAAU,EAAE;QACnB,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACxC,qFAAqF;QACrF,MAAM,UAAU,CAAC;KAClB;CACF;AAED,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,YAAY,GAAG,OAAO,CAAC;AAC7B,IAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC;IAAkC,gCAAQ;IAkBxC,sBAAY,IAAa,EAAE,IAAwB,EAAE,GAAqB;QAA1E,YACE,kBAAM,GAAG,CAAC,SAqHX;QAnHC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;SAC/D;QAED,uBAAuB;QACvB,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QAClB,IAAI,GAAG,IAAI,IAAI,YAAY,CAAC;QAC5B,GAAG,GAAG,GAAG,IAAI,EAAE,CAAC;QAChB,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC;QAEjC,KAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,IAAI,uBAAY,CAAC;QACtC,KAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,IAAI,uBAAY,CAAC;QACtC,IAAM,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAC1B,IAAM,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAC1B,IAAM,GAAG,GAAG,cAAM,CAAC,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;QAEhC,IAAI,GAAG,CAAC,GAAG,KAAK,OAAO,CAAC,GAAG,EAAE;YAC3B,KAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;SACxB;QAED,IAAM,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;QACrC,IAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,YAAY,CAAC;QAClD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;QAChB,IAAM,SAAS,GAAG,KAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QAEtC,IAAM,QAAQ,GAAG,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAEtE,IAAM,MAAM,GAAG,UAAC,IAAY,EAAE,MAAc;YAC1C,uEAAuE;YACvE,aAAa;YACb,IAAI,CAAC,KAAI,CAAC,aAAa,EAAE;gBACvB,IAAI,KAAI,CAAC,WAAW,EAAE;oBACpB,OAAO;iBACR;gBACD,KAAI,CAAC,WAAW,GAAG,IAAI,CAAC;gBACxB,iEAAiE;gBACjE,sEAAsE;gBACtE,8BAA8B;gBAC9B,IAAI,SAAO,GAAG,UAAU,CAAC;oBACvB,SAAO,GAAG,IAAI,CAAC;oBACf,+DAA+D;oBAC/D,KAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;gBACzB,CAAC,EAAE,yBAAyB,CAAC,CAAC;gBAC9B,KAAI,CAAC,IAAI,CAAC,OAAO,EAAE;oBACjB,IAAI,SAAO,KAAK,IAAI,EAAE;wBACpB,YAAY,CAAC,SAAO,CAAC,CAAC;qBACvB;oBACD,KAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;gBAClC,CAAC,CAAC,CAAC;gBACH,OAAO;aACR;YACD,KAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QAClC,CAAC,CAAC;QAEF,OAAO;QACP,IAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,KAAI,CAAC,KAAK,EAAE,KAAI,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,QAAQ,KAAK,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC;QAEnH,KAAI,CAAC,OAAO,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACvC,IAAI,QAAQ,KAAK,IAAI,EAAE;YACrB,KAAI,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SACpC;QAED,QAAQ;QACR,KAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,UAAC,GAAQ;YAChC,kDAAkD;YAClD,IAAI,GAAG,CAAC,IAAI,EAAE;gBACZ,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;oBAC/B,OAAO;iBACR;aACF;YAED,QAAQ;YACR,KAAI,CAAC,MAAM,EAAE,CAAC;YACd,kCAAkC;YAClC,IAAI,CAAC,KAAI,CAAC,aAAa,EAAE;gBACvB,KAAI,CAAC,aAAa,GAAG,IAAI,CAAC;gBAC1B,KAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;aACpB;YAED,0EAA0E;YAC1E,gBAAgB;YAChB,yBAAyB;YACzB,2BAA2B;YAC3B,IAAI,GAAG,CAAC,IAAI,EAAE;gBACZ,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;oBAC5D,OAAO;iBACR;aACF;YAED,sBAAsB;YACtB,IAAI,KAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;gBACtC,MAAM,GAAG,CAAC;aACX;QACH,CAAC,CAAC,CAAC;QAEH,KAAI,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC;QACrB,KAAI,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC;QACnB,KAAI,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC;QAErB,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAElB,KAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,KAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,KAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE;YACvB,IAAI,KAAI,CAAC,aAAa,EAAE;gBACtB,OAAO;aACR;YACD,KAAI,CAAC,aAAa,GAAG,IAAI,CAAC;YAC1B,KAAI,CAAC,MAAM,EAAE,CAAC;YACd,KAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACrB,CAAC,CAAC,CAAC;QAEH,KAAI,CAAC,cAAc,EAAE,CAAC;;IACxB,CAAC;IAzHD,sBAAW,gCAAM;aAAjB,cAAkC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;;;OAAA;IACxD,sBAAW,+BAAK;aAAhB,cAAiC,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;;;OAAA;IA0H5C,6BAAM,GAAhB,UAAiB,IAAY;QAC3B,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IAED;;OAEG;IAEW,iBAAI,GAAlB,UAAmB,GAAoB;QACrC,IAAM,IAAI,GAAiB,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;QACjE,GAAG,GAAG,GAAG,IAAI,EAAE,CAAC;QAEhB,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;YACxB,GAAG,GAAG;gBACJ,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;gBAClB,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;aACnB,CAAC;SACH;QAED,IAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,uBAAY,CAAC;QACtC,IAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,uBAAY,CAAC;QACtC,IAAM,QAAQ,GAAG,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAEtE,OAAO;QACP,IAAM,IAAI,GAAqB,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAEpD,IAAI,CAAC,OAAO,GAAG,IAAI,UAAU,CAAS,IAAI,CAAC,MAAM,CAAC,CAAC;QACnD,IAAI,QAAQ,KAAK,IAAI,EAAE;YACnB,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SACtC;QACD,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QAEtB,IAAI,CAAC,MAAM,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,QAAQ,KAAK,IAAI,EAAE;YACnB,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SACrC;QACD,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QAErB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC;QAErB,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC;QACvC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC;QAEpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,UAAA,GAAG;YAC1B,IAAI,CAAC,MAAM,EAAE,CAAC;YACd,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;gBACtC,MAAM,GAAG,CAAC;aACX;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE;YACvB,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,8BAAO,GAAd;QAAA,iBAUC;QATC,IAAI,CAAC,MAAM,EAAE,CAAC;QAEd,kEAAkE;QAClE,mDAAmD;QACnD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE;YACzB,KAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAEM,2BAAI,GAAX,UAAY,MAAe;QACzB,IAAI;YACF,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,IAAI,QAAQ,CAAC,CAAC;SAC5C;QAAC,OAAO,CAAC,EAAE,EAAE,aAAa,EAAE;IAC/B,CAAC;IAKD,sBAAW,iCAAO;QAHlB;;WAEG;aACH;YACE,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC;QACxD,CAAC;;;OAAA;IAED;;OAEG;IAEI,6BAAM,GAAb,UAAc,IAAY,EAAE,IAAY;QACtC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,QAAQ,EAAE;YAClG,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QACD,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAEO,mCAAY,GAApB,UAAqB,GAAgB;QACjC,yDAAyD;QACzD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC;QACnB,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC;QAExB,2DAA2D;QAC3D,iDAAiD;QACjD,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;QAClB,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC;QAErB,yDAAyD;QACzD,OAAO,GAAG,CAAC,UAAU,CAAC,CAAC;QACvB,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QACtB,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QACtB,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;IACH,mBAAC;AAAD,CAAC,AA/PD,CAAkC,mBAAQ,GA+PzC;AA/PY,oCAAY;AAiQzB;;;;GAIG;AACH;IAAyB,8BAAU;IACjC,oBAAY,EAAU;QAAtB,iBAMC;QALO,IAAA,iCAAyD,EAAvD,cAAI,EAAE,wBAAiD,CAAC,CAAC,sBAAsB;QACvF,8FAA8F;QAC9F,IAAM,MAAM,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAChB,QAAA,kBAAW,EAAE,MAAM,QAAA,EAAE,CAAC,SAAC;;IACzB,CAAC;IACH,iBAAC;AAAD,CAAC,AARD,CAAyB,GAAG,CAAC,MAAM,GAQlC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..62799e3bd886ef2954cca61dd85b8d064857fd11
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,100 @@@
++"use strict";
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var unixTerminal_1 = require("./unixTerminal");
++var assert = require("assert");
++var path = require("path");
++var testUtils_test_1 = require("./testUtils.test");
++var FIXTURES_PATH = path.normalize(path.join(__dirname, '..', 'fixtures', 'utf8-character.txt'));
++if (process.platform !== 'win32') {
++    describe('UnixTerminal', function () {
++        describe('Constructor', function () {
++            it('should set a valid pts name', function () {
++                var term = new unixTerminal_1.UnixTerminal('/bin/bash', [], {});
++                var regExp;
++                if (process.platform === 'linux') {
++                    // https://linux.die.net/man/4/pts
++                    regExp = /^\/dev\/pts\/\d+$/;
++                }
++                if (process.platform === 'darwin') {
++                    // https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man4/pty.4.html
++                    regExp = /^\/dev\/tty[p-sP-S][a-z0-9]+$/;
++                }
++                if (regExp) {
++                    assert.ok(regExp.test(term._pty), '"' + term._pty + '" should match ' + regExp.toString());
++                }
++            });
++        });
++        describe('PtyForkEncodingOption', function () {
++            it('should default to utf8', function (done) {
++                var term = new unixTerminal_1.UnixTerminal('/bin/bash', ['-c', "cat \"" + FIXTURES_PATH + "\""]);
++                term.on('data', function (data) {
++                    assert.equal(typeof data, 'string');
++                    assert.equal(data, '\u00E6');
++                    done();
++                });
++            });
++            it('should return a Buffer when encoding is null', function (done) {
++                var term = new unixTerminal_1.UnixTerminal('/bin/bash', ['-c', "cat \"" + FIXTURES_PATH + "\""], {
++                    encoding: null
++                });
++                term.on('data', function (data) {
++                    assert.equal(typeof data, 'object');
++                    assert.ok(data instanceof Buffer);
++                    assert.equal(0xC3, data[0]);
++                    assert.equal(0xA6, data[1]);
++                    done();
++                });
++            });
++            it('should support other encodings', function (done) {
++                var text = 'test æ!';
++                var term = new unixTerminal_1.UnixTerminal(null, ['-c', 'echo "' + text + '"'], {
++                    encoding: 'base64'
++                });
++                var buffer = '';
++                term.on('data', function (data) {
++                    assert.equal(typeof data, 'string');
++                    buffer += data;
++                });
++                term.on('exit', function () {
++                    assert.equal(Buffer.alloc(8, buffer, 'base64').toString().replace('\r', '').replace('\n', ''), text);
++                    done();
++                });
++            });
++        });
++        describe('open', function () {
++            var term;
++            afterEach(function () {
++                if (term) {
++                    term.slave.destroy();
++                    term.master.destroy();
++                }
++            });
++            it('should open a pty with access to a master and slave socket', function (done) {
++                var doneCalled = false;
++                term = unixTerminal_1.UnixTerminal.open({});
++                var slavebuf = '';
++                term.slave.on('data', function (data) {
++                    slavebuf += data;
++                });
++                var masterbuf = '';
++                term.master.on('data', function (data) {
++                    masterbuf += data;
++                });
++                testUtils_test_1.pollUntil(function () {
++                    if (masterbuf === 'slave\r\nmaster\r\n' && slavebuf === 'master\n') {
++                        done();
++                        return true;
++                    }
++                    return false;
++                }, 200, 10);
++                term.slave.write('slave\n');
++                term.master.write('master\n');
++            });
++        });
++    });
++}
++//# sourceMappingURL=unixTerminal.test.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8a360acb43bf0626d87adb27f1bd413324d8e4bb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"unixTerminal.test.js","sourceRoot":"","sources":["../src/unixTerminal.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,+CAA8C;AAC9C,+BAAiC;AACjC,2BAA6B;AAC7B,mDAA6C;AAE7C,IAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,EAAE,oBAAoB,CAAC,CAAC,CAAC;AAEnG,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,QAAQ,CAAC,cAAc,EAAE;QACvB,QAAQ,CAAC,aAAa,EAAE;YACtB,EAAE,CAAC,6BAA6B,EAAE;gBAChC,IAAM,IAAI,GAAG,IAAI,2BAAY,CAAC,WAAW,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;gBACnD,IAAI,MAAM,CAAC;gBACX,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;oBAChC,kCAAkC;oBAClC,MAAM,GAAG,mBAAmB,CAAC;iBAC9B;gBACD,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE;oBACjC,qGAAqG;oBACrG,MAAM,GAAG,+BAA+B,CAAC;iBAC1C;gBACD,IAAI,MAAM,EAAE;oBACV,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAO,IAAK,CAAC,IAAI,CAAC,EAAE,GAAG,GAAS,IAAK,CAAC,IAAI,GAAG,iBAAiB,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;iBAC1G;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,uBAAuB,EAAE;YAChC,EAAE,CAAC,wBAAwB,EAAE,UAAC,IAAI;gBAChC,IAAM,IAAI,GAAG,IAAI,2BAAY,CAAC,WAAW,EAAE,CAAE,IAAI,EAAE,WAAQ,aAAa,OAAG,CAAE,CAAC,CAAC;gBAC/E,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;oBAC7B,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,8CAA8C,EAAE,UAAC,IAAI;gBACtD,IAAM,IAAI,GAAG,IAAI,2BAAY,CAAC,WAAW,EAAE,CAAE,IAAI,EAAE,WAAQ,aAAa,OAAG,CAAE,EAAE;oBAC7E,QAAQ,EAAE,IAAI;iBACf,CAAC,CAAC;gBACH,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpC,MAAM,CAAC,EAAE,CAAC,IAAI,YAAY,MAAM,CAAC,CAAC;oBAClC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC5B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC5B,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,gCAAgC,EAAE,UAAC,IAAI;gBACxC,IAAM,IAAI,GAAG,SAAS,CAAC;gBACvB,IAAM,IAAI,GAAG,IAAI,2BAAY,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI,GAAG,GAAG,CAAC,EAAE;oBACjE,QAAQ,EAAE,QAAQ;iBACnB,CAAC,CAAC;gBACH,IAAI,MAAM,GAAG,EAAE,CAAC;gBAChB,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpC,MAAM,IAAI,IAAI,CAAC;gBACjB,CAAC,CAAC,CAAC;gBACH,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;oBACd,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;oBACrG,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,MAAM,EAAE;YACf,IAAI,IAAkB,CAAC;YAEvB,SAAS,CAAC;gBACR,IAAI,IAAI,EAAE;oBACR,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;oBACrB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;iBACvB;YACH,CAAC,CAAC,CAAC;YAEH,EAAE,CAAC,4DAA4D,EAAE,UAAC,IAAI;gBACpE,IAAI,UAAU,GAAG,KAAK,CAAC;gBACvB,IAAI,GAAG,2BAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAE7B,IAAI,QAAQ,GAAG,EAAE,CAAC;gBAClB,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACzB,QAAQ,IAAI,IAAI,CAAC;gBACnB,CAAC,CAAC,CAAC;gBAEH,IAAI,SAAS,GAAG,EAAE,CAAC;gBACnB,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBAC1B,SAAS,IAAI,IAAI,CAAC;gBACpB,CAAC,CAAC,CAAC;gBAEH,0BAAS,CAAC;oBACR,IAAI,SAAS,KAAK,qBAAqB,IAAI,QAAQ,KAAK,UAAU,EAAE;wBAClE,IAAI,EAAE,CAAC;wBACP,OAAO,IAAI,CAAC;qBACb;oBACD,OAAO,KAAK,CAAC;gBACf,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;gBAEZ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;gBAC5B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..89639c4a664f9c09b1b7acec7dfae445983abb03
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,16 @@@
++"use strict";
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++function assign(target) {
++    var sources = [];
++    for (var _i = 1; _i < arguments.length; _i++) {
++        sources[_i - 1] = arguments[_i];
++    }
++    sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return target[key] = source[key]; }); });
++    return target;
++}
++exports.assign = assign;
++//# sourceMappingURL=utils.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..bd5694330a72ce36081ae2d37424f812530da990
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,SAAgB,MAAM,CAAC,MAAW;IAAE,iBAAiB;SAAjB,UAAiB,EAAjB,qBAAiB,EAAjB,IAAiB;QAAjB,gCAAiB;;IACnD,OAAO,CAAC,OAAO,CAAC,UAAA,MAAM,IAAI,OAAA,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,UAAA,GAAG,IAAI,OAAA,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,EAAzB,CAAyB,CAAC,EAA7D,CAA6D,CAAC,CAAC;IACzF,OAAO,MAAM,CAAC;AAChB,CAAC;AAHD,wBAGC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4ef3fd678c3f84a37e663f92208b2631d50032cd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,310 @@@
++"use strict";
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var os = require("os");
++var path = require("path");
++var net_1 = require("net");
++var child_process_1 = require("child_process");
++var conptyNative;
++var winptyNative;
++/**
++ * The amount of time to wait for additional data after the conpty shell process has exited before
++ * shutting down the socket. The timer will be reset if a new data event comes in after the timer
++ * has started.
++ */
++var FLUSH_DATA_INTERVAL = 20;
++/**
++ * This agent sits between the WindowsTerminal class and provides a common interface for both conpty
++ * and winpty.
++ */
++var WindowsPtyAgent = /** @class */ (function () {
++    function WindowsPtyAgent(file, args, env, cwd, cols, rows, debug, _useConpty, conptyInheritCursor) {
++        var _this = this;
++        if (conptyInheritCursor === void 0) { conptyInheritCursor = false; }
++        this._useConpty = _useConpty;
++        if (this._useConpty === undefined || this._useConpty === true) {
++            this._useConpty = this._getWindowsBuildNumber() >= 18309;
++        }
++        if (this._useConpty) {
++            if (!conptyNative) {
++                try {
++                    conptyNative = require('../build/Release/conpty.node');
++                }
++                catch (outerError) {
++                    try {
++                        conptyNative = require('../build/Debug/conpty.node');
++                    }
++                    catch (innerError) {
++                        console.error('innerError', innerError);
++                        // Re-throw the exception from the Release require if the Debug require fails as well
++                        throw outerError;
++                    }
++                }
++            }
++        }
++        else {
++            if (!winptyNative) {
++                try {
++                    winptyNative = require('../build/Release/pty.node');
++                }
++                catch (outerError) {
++                    try {
++                        winptyNative = require('../build/Debug/pty.node');
++                    }
++                    catch (innerError) {
++                        console.error('innerError', innerError);
++                        // Re-throw the exception from the Release require if the Debug require fails as well
++                        throw outerError;
++                    }
++                }
++            }
++        }
++        this._ptyNative = this._useConpty ? conptyNative : winptyNative;
++        // Sanitize input variable.
++        cwd = path.resolve(cwd);
++        // Compose command line
++        var commandLine = argsToCommandLine(file, args);
++        // Open pty session.
++        var term;
++        if (this._useConpty) {
++            term = this._ptyNative.startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor);
++        }
++        else {
++            term = this._ptyNative.startProcess(file, commandLine, env, cwd, cols, rows, debug);
++            this._pid = term.pid;
++            this._innerPid = term.innerPid;
++            this._innerPidHandle = term.innerPidHandle;
++        }
++        // Not available on windows.
++        this._fd = term.fd;
++        // Generated incremental number that has no real purpose besides  using it
++        // as a terminal id.
++        this._pty = term.pty;
++        // Create terminal pipe IPC channel and forward to a local unix socket.
++        this._outSocket = new net_1.Socket();
++        this._outSocket.setEncoding('utf8');
++        this._outSocket.connect(term.conout, function () {
++            // TODO: Emit event on agent instead of socket?
++            // Emit ready event.
++            _this._outSocket.emit('ready_datapipe');
++        });
++        this._inSocket = new net_1.Socket();
++        this._inSocket.setEncoding('utf8');
++        this._inSocket.connect(term.conin);
++        // TODO: Wait for ready event?
++        if (this._useConpty) {
++            var connect = this._ptyNative.connect(this._pty, commandLine, cwd, env, function (c) { return _this._$onProcessExit(c); });
++            this._innerPid = connect.pid;
++        }
++    }
++    Object.defineProperty(WindowsPtyAgent.prototype, "inSocket", {
++        get: function () { return this._inSocket; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(WindowsPtyAgent.prototype, "outSocket", {
++        get: function () { return this._outSocket; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(WindowsPtyAgent.prototype, "fd", {
++        get: function () { return this._fd; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(WindowsPtyAgent.prototype, "innerPid", {
++        get: function () { return this._innerPid; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(WindowsPtyAgent.prototype, "pty", {
++        get: function () { return this._pty; },
++        enumerable: true,
++        configurable: true
++    });
++    WindowsPtyAgent.prototype.resize = function (cols, rows) {
++        if (this._useConpty) {
++            if (this._exitCode !== undefined) {
++                throw new Error('Cannot resize a pty that has already exited');
++            }
++            this._ptyNative.resize(this._pty, cols, rows);
++            return;
++        }
++        this._ptyNative.resize(this._pid, cols, rows);
++    };
++    WindowsPtyAgent.prototype.kill = function () {
++        var _this = this;
++        this._inSocket.readable = false;
++        this._inSocket.writable = false;
++        this._outSocket.readable = false;
++        this._outSocket.writable = false;
++        // Tell the agent to kill the pty, this releases handles to the process
++        if (this._useConpty) {
++            this._getConsoleProcessList().then(function (consoleProcessList) {
++                consoleProcessList.forEach(function (pid) {
++                    try {
++                        process.kill(pid);
++                    }
++                    catch (e) {
++                        // Ignore if process cannot be found (kill ESRCH error)
++                    }
++                });
++                _this._ptyNative.kill(_this._pty);
++            });
++        }
++        else {
++            this._ptyNative.kill(this._pid, this._innerPidHandle);
++            // Since pty.kill closes the handle it will kill most processes by itself
++            // and process IDs can be reused as soon as all handles to them are
++            // dropped, we want to immediately kill the entire console process list.
++            // If we do not force kill all processes here, node servers in particular
++            // seem to become detached and remain running (see
++            // Microsoft/vscode#26807).
++            var processList = this._ptyNative.getProcessList(this._pid);
++            processList.forEach(function (pid) {
++                try {
++                    process.kill(pid);
++                }
++                catch (e) {
++                    // Ignore if process cannot be found (kill ESRCH error)
++                }
++            });
++        }
++    };
++    WindowsPtyAgent.prototype._getConsoleProcessList = function () {
++        var _this = this;
++        return new Promise(function (resolve) {
++            var agent = child_process_1.fork(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()]);
++            agent.on('message', function (message) {
++                clearTimeout(timeout);
++                resolve(message.consoleProcessList);
++            });
++            var timeout = setTimeout(function () {
++                // Something went wrong, just send back the shell PID
++                agent.kill();
++                resolve([_this._innerPid]);
++            }, 5000);
++        });
++    };
++    Object.defineProperty(WindowsPtyAgent.prototype, "exitCode", {
++        get: function () {
++            if (this._useConpty) {
++                return this._exitCode;
++            }
++            return this._ptyNative.getExitCode(this._innerPidHandle);
++        },
++        enumerable: true,
++        configurable: true
++    });
++    WindowsPtyAgent.prototype._getWindowsBuildNumber = function () {
++        var osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
++        var buildNumber = 0;
++        if (osVersion && osVersion.length === 4) {
++            buildNumber = parseInt(osVersion[3]);
++        }
++        return buildNumber;
++    };
++    WindowsPtyAgent.prototype._generatePipeName = function () {
++        return "conpty-" + Math.random() * 10000000;
++    };
++    /**
++     * Triggered from the native side when a contpy process exits.
++     */
++    WindowsPtyAgent.prototype._$onProcessExit = function (exitCode) {
++        var _this = this;
++        this._exitCode = exitCode;
++        this._flushDataAndCleanUp();
++        this._outSocket.on('data', function () { return _this._flushDataAndCleanUp(); });
++    };
++    WindowsPtyAgent.prototype._flushDataAndCleanUp = function () {
++        var _this = this;
++        if (this._closeTimeout) {
++            clearTimeout(this._closeTimeout);
++        }
++        this._closeTimeout = setTimeout(function () { return _this._cleanUpProcess(); }, FLUSH_DATA_INTERVAL);
++    };
++    WindowsPtyAgent.prototype._cleanUpProcess = function () {
++        this._inSocket.readable = false;
++        this._inSocket.writable = false;
++        this._outSocket.readable = false;
++        this._outSocket.writable = false;
++        this._outSocket.destroy();
++    };
++    return WindowsPtyAgent;
++}());
++exports.WindowsPtyAgent = WindowsPtyAgent;
++// Convert argc/argv into a Win32 command-line following the escaping convention
++// documented on MSDN (e.g. see CommandLineToArgvW documentation). Copied from
++// winpty project.
++function argsToCommandLine(file, args) {
++    if (isCommandLine(args)) {
++        if (args.length === 0) {
++            return file;
++        }
++        return argsToCommandLine(file, []) + " " + args;
++    }
++    var argv = [file];
++    Array.prototype.push.apply(argv, args);
++    var result = '';
++    for (var argIndex = 0; argIndex < argv.length; argIndex++) {
++        if (argIndex > 0) {
++            result += ' ';
++        }
++        var arg = argv[argIndex];
++        // if it is empty or it contains whitespace and is not already quoted
++        var hasLopsidedEnclosingQuote = xOr((arg[0] !== '"'), (arg[arg.length - 1] !== '"'));
++        var hasNoEnclosingQuotes = ((arg[0] !== '"') && (arg[arg.length - 1] !== '"'));
++        var quote = arg === '' ||
++            (arg.indexOf(' ') !== -1 ||
++                arg.indexOf('\t') !== -1) &&
++                ((arg.length > 1) &&
++                    (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
++        if (quote) {
++            result += '\"';
++        }
++        var bsCount = 0;
++        for (var i = 0; i < arg.length; i++) {
++            var p = arg[i];
++            if (p === '\\') {
++                bsCount++;
++            }
++            else if (p === '"') {
++                result += repeatText('\\', bsCount * 2 + 1);
++                result += '"';
++                bsCount = 0;
++            }
++            else {
++                result += repeatText('\\', bsCount);
++                bsCount = 0;
++                result += p;
++            }
++        }
++        if (quote) {
++            result += repeatText('\\', bsCount * 2);
++            result += '\"';
++        }
++        else {
++            result += repeatText('\\', bsCount);
++        }
++    }
++    return result;
++}
++exports.argsToCommandLine = argsToCommandLine;
++function isCommandLine(args) {
++    return typeof args === 'string';
++}
++function repeatText(text, count) {
++    var result = '';
++    for (var i = 0; i < count; i++) {
++        result += text;
++    }
++    return result;
++}
++function xOr(arg1, arg2) {
++    return ((arg1 && !arg2) || (!arg1 && arg2));
++}
++//# sourceMappingURL=windowsPtyAgent.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b8d1b0573680c1985da9c9dbf9ceb06adfddf3ad
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"windowsPtyAgent.js","sourceRoot":"","sources":["../src/windowsPtyAgent.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,uBAAyB;AACzB,2BAA6B;AAC7B,2BAA6B;AAE7B,+CAAqC;AAErC,IAAI,YAA2B,CAAC;AAChC,IAAI,YAA2B,CAAC;AAEhC;;;;GAIG;AACH,IAAM,mBAAmB,GAAG,EAAE,CAAC;AAE/B;;;GAGG;AACH;IAmBE,yBACE,IAAY,EACZ,IAAuB,EACvB,GAAa,EACb,GAAW,EACX,IAAY,EACZ,IAAY,EACZ,KAAc,EACN,UAA+B,EACvC,mBAAoC;QATtC,iBAyFC;QAhFC,oCAAA,EAAA,2BAAoC;QAD5B,eAAU,GAAV,UAAU,CAAqB;QAGvC,IAAI,IAAI,CAAC,UAAU,KAAK,SAAS,IAAI,IAAI,CAAC,UAAU,KAAK,IAAI,EAAE;YAC7D,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,sBAAsB,EAAE,IAAI,KAAK,CAAC;SAC1D;QACD,IAAI,IAAI,CAAC,UAAU,EAAE;YACnB,IAAI,CAAC,YAAY,EAAE;gBACjB,IAAI;oBACF,YAAY,GAAG,OAAO,CAAC,8BAA8B,CAAC,CAAC;iBACxD;gBAAC,OAAO,UAAU,EAAE;oBACnB,IAAI;wBACF,YAAY,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAC;qBACtD;oBAAC,OAAO,UAAU,EAAE;wBACnB,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;wBACxC,qFAAqF;wBACrF,MAAM,UAAU,CAAC;qBAClB;iBACF;aACF;SACF;aAAM;YACL,IAAI,CAAC,YAAY,EAAE;gBACjB,IAAI;oBACF,YAAY,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;iBACrD;gBAAC,OAAO,UAAU,EAAE;oBACnB,IAAI;wBACF,YAAY,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;qBACnD;oBAAC,OAAO,UAAU,EAAE;wBACnB,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;wBACxC,qFAAqF;wBACrF,MAAM,UAAU,CAAC;qBAClB;iBACF;aACF;SACF;QACD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC;QAEhE,2BAA2B;QAC3B,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAExB,uBAAuB;QACvB,IAAM,WAAW,GAAG,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAElD,oBAAoB;QACpB,IAAI,IAAqC,CAAC;QAC1C,IAAI,IAAI,CAAC,UAAU,EAAE;YACnB,IAAI,GAAI,IAAI,CAAC,UAA4B,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,iBAAiB,EAAE,EAAE,mBAAmB,CAAC,CAAC;SAChI;aAAM;YACL,IAAI,GAAI,IAAI,CAAC,UAA4B,CAAC,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;YACvG,IAAI,CAAC,IAAI,GAAI,IAAuB,CAAC,GAAG,CAAC;YACzC,IAAI,CAAC,SAAS,GAAI,IAAuB,CAAC,QAAQ,CAAC;YACnD,IAAI,CAAC,eAAe,GAAI,IAAuB,CAAC,cAAc,CAAC;SAChE;QAED,4BAA4B;QAC5B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC;QAEnB,0EAA0E;QAC1E,oBAAoB;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC;QAErB,uEAAuE;QACvE,IAAI,CAAC,UAAU,GAAG,IAAI,YAAM,EAAE,CAAC;QAC/B,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE;YACnC,+CAA+C;YAE/C,oBAAoB;YACpB,KAAI,CAAC,UAAU,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,SAAS,GAAG,IAAI,YAAM,EAAE,CAAC;QAC9B,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnC,8BAA8B;QAE9B,IAAI,IAAI,CAAC,UAAU,EAAE;YACnB,IAAM,OAAO,GAAI,IAAI,CAAC,UAA4B,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,EAAE,UAAA,CAAC,IAAI,OAAA,KAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAvB,CAAuB,CAC9H,CAAC;YACI,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC;SAC9B;IACH,CAAC;IA/FD,sBAAW,qCAAQ;aAAnB,cAAgC,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;;;OAAA;IACxD,sBAAW,sCAAS;aAApB,cAAiC,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;;;OAAA;IAC1D,sBAAW,+BAAE;aAAb,cAAuB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;;;OAAA;IACzC,sBAAW,qCAAQ;aAAnB,cAAgC,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;;;OAAA;IACxD,sBAAW,gCAAG;aAAd,cAA2B,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;;;OAAA;IA6FvC,gCAAM,GAAb,UAAc,IAAY,EAAE,IAAY;QACtC,IAAI,IAAI,CAAC,UAAU,EAAE;YACnB,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE;gBAChC,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;aAChE;YACD,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YAC9C,OAAO;SACR;QACD,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAChD,CAAC;IAEM,8BAAI,GAAX;QAAA,iBAkCC;QAjCC,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,KAAK,CAAC;QAChC,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,KAAK,CAAC;QAChC,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;QACjC,uEAAuE;QACvE,IAAI,IAAI,CAAC,UAAU,EAAE;YACnB,IAAI,CAAC,sBAAsB,EAAE,CAAC,IAAI,CAAC,UAAA,kBAAkB;gBACnD,kBAAkB,CAAC,OAAO,CAAC,UAAC,GAAW;oBACrC,IAAI;wBACF,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;qBACnB;oBAAC,OAAO,CAAC,EAAE;wBACV,uDAAuD;qBACxD;gBACH,CAAC,CAAC,CAAC;gBACF,KAAI,CAAC,UAA4B,CAAC,IAAI,CAAC,KAAI,CAAC,IAAI,CAAC,CAAC;YACrD,CAAC,CAAC,CAAC;SACJ;aAAM;YACJ,IAAI,CAAC,UAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;YACzE,yEAAyE;YACzE,mEAAmE;YACnE,wEAAwE;YACxE,yEAAyE;YACzE,kDAAkD;YAClD,2BAA2B;YAC3B,IAAM,WAAW,GAAc,IAAI,CAAC,UAA4B,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC3F,WAAW,CAAC,OAAO,CAAC,UAAA,GAAG;gBACrB,IAAI;oBACF,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;iBACnB;gBAAC,OAAO,CAAC,EAAE;oBACV,uDAAuD;iBACxD;YACH,CAAC,CAAC,CAAC;SACJ;IACH,CAAC;IAEO,gDAAsB,GAA9B;QAAA,iBAaC;QAZC,OAAO,IAAI,OAAO,CAAW,UAAA,OAAO;YAClC,IAAM,KAAK,GAAG,oBAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,2BAA2B,CAAC,EAAE,CAAE,KAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAE,CAAC,CAAC;YACrG,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,UAAA,OAAO;gBACzB,YAAY,CAAC,OAAO,CAAC,CAAC;gBACtB,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;YACtC,CAAC,CAAC,CAAC;YACH,IAAM,OAAO,GAAG,UAAU,CAAC;gBACzB,qDAAqD;gBACrD,KAAK,CAAC,IAAI,EAAE,CAAC;gBACb,OAAO,CAAC,CAAE,KAAI,CAAC,SAAS,CAAE,CAAC,CAAC;YAC9B,CAAC,EAAE,IAAI,CAAC,CAAC;QACX,CAAC,CAAC,CAAC;IACL,CAAC;IAED,sBAAW,qCAAQ;aAAnB;YACE,IAAI,IAAI,CAAC,UAAU,EAAE;gBACnB,OAAO,IAAI,CAAC,SAAS,CAAC;aACvB;YACD,OAAQ,IAAI,CAAC,UAA4B,CAAC,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAC9E,CAAC;;;OAAA;IAEO,gDAAsB,GAA9B;QACE,IAAM,SAAS,GAAG,CAAC,sBAAsB,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9D,IAAI,WAAW,GAAW,CAAC,CAAC;QAC5B,IAAI,SAAS,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;YACvC,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;SACtC;QACD,OAAO,WAAW,CAAC;IACrB,CAAC;IAEO,2CAAiB,GAAzB;QACE,OAAO,YAAU,IAAI,CAAC,MAAM,EAAE,GAAG,QAAU,CAAC;IAC9C,CAAC;IAED;;OAEG;IACK,yCAAe,GAAvB,UAAwB,QAAgB;QAAxC,iBAIC;QAHC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC5B,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,cAAM,OAAA,KAAI,CAAC,oBAAoB,EAAE,EAA3B,CAA2B,CAAC,CAAC;IAChE,CAAC;IAEO,8CAAoB,GAA5B;QAAA,iBAKC;QAJC,IAAI,IAAI,CAAC,aAAa,EAAE;YACtB,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;SAClC;QACD,IAAI,CAAC,aAAa,GAAG,UAAU,CAAC,cAAM,OAAA,KAAI,CAAC,eAAe,EAAE,EAAtB,CAAsB,EAAE,mBAAmB,CAAC,CAAC;IACrF,CAAC;IAEO,yCAAe,GAAvB;QACE,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,KAAK,CAAC;QAChC,IAAI,CAAC,SAAS,CAAC,QAAQ,GAAG,KAAK,CAAC;QAChC,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;IACH,sBAAC;AAAD,CAAC,AAvND,IAuNC;AAvNY,0CAAe;AAyN5B,gFAAgF;AAChF,8EAA8E;AAC9E,kBAAkB;AAClB,SAAgB,iBAAiB,CAAC,IAAY,EAAE,IAAuB;IACrE,IAAI,aAAa,CAAC,IAAI,CAAC,EAAE;QACvB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;YACrB,OAAO,IAAI,CAAC;SACb;QACD,OAAU,iBAAiB,CAAC,IAAI,EAAE,EAAE,CAAC,SAAI,IAAM,CAAC;KACjD;IACD,IAAM,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;IACpB,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,QAAQ,GAAG,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE;QACzD,IAAI,QAAQ,GAAG,CAAC,EAAE;YAChB,MAAM,IAAI,GAAG,CAAC;SACf;QACD,IAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC3B,qEAAqE;QACrE,IAAM,yBAAyB,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QACvF,IAAM,oBAAoB,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QACjF,IAAM,KAAK,GACT,GAAG,KAAK,EAAE;YACV,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;gBACxB,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;gBACzB,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;oBACjB,CAAC,yBAAyB,IAAI,oBAAoB,CAAC,CAAC,CAAC;QACvD,IAAI,KAAK,EAAE;YACT,MAAM,IAAI,IAAI,CAAC;SAChB;QACD,IAAI,OAAO,GAAG,CAAC,CAAC;QAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACnC,IAAM,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;YACjB,IAAI,CAAC,KAAK,IAAI,EAAE;gBACd,OAAO,EAAE,CAAC;aACX;iBAAM,IAAI,CAAC,KAAK,GAAG,EAAE;gBACpB,MAAM,IAAI,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;gBAC5C,MAAM,IAAI,GAAG,CAAC;gBACd,OAAO,GAAG,CAAC,CAAC;aACb;iBAAM;gBACL,MAAM,IAAI,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;gBACpC,OAAO,GAAG,CAAC,CAAC;gBACZ,MAAM,IAAI,CAAC,CAAC;aACb;SACF;QACD,IAAI,KAAK,EAAE;YACT,MAAM,IAAI,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,IAAI,CAAC;SAChB;aAAM;YACL,MAAM,IAAI,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;SACrC;KACF;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAlDD,8CAkDC;AAED,SAAS,aAAa,CAAC,IAAuB;IAC5C,OAAO,OAAO,IAAI,KAAK,QAAQ,CAAC;AAClC,CAAC;AAED,SAAS,UAAU,CAAC,IAAY,EAAE,KAAa;IAC7C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;QAC9B,MAAM,IAAI,IAAI,CAAC;KAChB;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,GAAG,CAAC,IAAa,EAAE,IAAa;IACvC,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC;AAC9C,CAAC"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..15bbf5ba397ab02a5ec6a11b1c0c6f6ffd137be0
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,90 @@@
++"use strict";
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var assert = require("assert");
++var windowsPtyAgent_1 = require("./windowsPtyAgent");
++function check(file, args, expected) {
++    assert.equal(windowsPtyAgent_1.argsToCommandLine(file, args), expected);
++}
++if (process.platform === 'win32') {
++    describe('argsToCommandLine', function () {
++        describe('Plain strings', function () {
++            it('doesn\'t quote plain string', function () {
++                check('asdf', [], 'asdf');
++            });
++            it('doesn\'t escape backslashes', function () {
++                check('\\asdf\\qwer\\', [], '\\asdf\\qwer\\');
++            });
++            it('doesn\'t escape multiple backslashes', function () {
++                check('asdf\\\\qwer', [], 'asdf\\\\qwer');
++            });
++            it('adds backslashes before quotes', function () {
++                check('"asdf"qwer"', [], '\\"asdf\\"qwer\\"');
++            });
++            it('escapes backslashes before quotes', function () {
++                check('asdf\\"qwer', [], 'asdf\\\\\\"qwer');
++            });
++        });
++        describe('Quoted strings', function () {
++            it('quotes string with spaces', function () {
++                check('asdf qwer', [], '"asdf qwer"');
++            });
++            it('quotes empty string', function () {
++                check('', [], '""');
++            });
++            it('quotes string with tabs', function () {
++                check('asdf\tqwer', [], '"asdf\tqwer"');
++            });
++            it('escapes only the last backslash', function () {
++                check('\\asdf \\qwer\\', [], '"\\asdf \\qwer\\\\"');
++            });
++            it('doesn\'t escape multiple backslashes', function () {
++                check('asdf \\\\qwer', [], '"asdf \\\\qwer"');
++            });
++            it('escapes backslashes before quotes', function () {
++                check('asdf \\"qwer', [], '"asdf \\\\\\"qwer"');
++            });
++            it('escapes multiple backslashes at the end', function () {
++                check('asdf qwer\\\\', [], '"asdf qwer\\\\\\\\"');
++            });
++        });
++        describe('Multiple arguments', function () {
++            it('joins arguments with spaces', function () {
++                check('asdf', ['qwer zxcv', '', '"'], 'asdf "qwer zxcv" "" \\"');
++            });
++            it('array argument all in quotes', function () {
++                check('asdf', ['"surounded by quotes"'], 'asdf \\"surounded by quotes\\"');
++            });
++            it('array argument quotes in the middle', function () {
++                check('asdf', ['quotes "in the" middle'], 'asdf "quotes \\"in the\\" middle"');
++            });
++            it('array argument quotes near start', function () {
++                check('asdf', ['"quotes" near start'], 'asdf "\\"quotes\\" near start"');
++            });
++            it('array argument quotes near end', function () {
++                check('asdf', ['quotes "near end"'], 'asdf "quotes \\"near end\\""');
++            });
++        });
++        describe('Args as CommandLine', function () {
++            it('should handle empty string', function () {
++                check('file', '', 'file');
++            });
++            it('should not change args', function () {
++                check('file', 'foo bar baz', 'file foo bar baz');
++                check('file', 'foo \\ba"r \baz', 'file foo \\ba"r \baz');
++            });
++        });
++        describe('Real-world cases', function () {
++            it('quotes within quotes', function () {
++                check('cmd.exe', ['/c', 'powershell -noexit -command \'Set-location \"C:\\user\"\''], 'cmd.exe /c "powershell -noexit -command \'Set-location \\\"C:\\user\\"\'"');
++            });
++            it('space within quotes', function () {
++                check('cmd.exe', ['/k', '"C:\\Users\\alros\\Desktop\\test script.bat"'], 'cmd.exe /k \\"C:\\Users\\alros\\Desktop\\test script.bat\\"');
++            });
++        });
++    });
++}
++//# sourceMappingURL=windowsPtyAgent.test.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..f92251ad10eec63dfd57df31e99531f7dcf2cf52
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"windowsPtyAgent.test.js","sourceRoot":"","sources":["../src/windowsPtyAgent.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,+BAAiC;AACjC,qDAAsD;AAEtD,SAAS,KAAK,CAAC,IAAY,EAAE,IAAuB,EAAE,QAAgB;IACpE,MAAM,CAAC,KAAK,CAAC,mCAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;AACxD,CAAC;AAED,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,QAAQ,CAAC,mBAAmB,EAAE;QAC5B,QAAQ,CAAC,eAAe,EAAE;YACxB,EAAE,CAAC,6BAA6B,EAAE;gBAChC,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,6BAA6B,EAAE;gBAChC,KAAK,CAAC,gBAAgB,EAAE,EAAE,EAAE,gBAAgB,CAAC,CAAC;YAChD,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,sCAAsC,EAAE;gBACzC,KAAK,CAAC,cAAc,EAAE,EAAE,EAAE,cAAc,CAAC,CAAC;YAC5C,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,gCAAgC,EAAE;gBACnC,KAAK,CAAC,aAAa,EAAE,EAAE,EAAE,mBAAmB,CAAC,CAAC;YAChD,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,mCAAmC,EAAE;gBACtC,KAAK,CAAC,aAAa,EAAE,EAAE,EAAE,iBAAiB,CAAC,CAAC;YAC9C,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,gBAAgB,EAAE;YACzB,EAAE,CAAC,2BAA2B,EAAE;gBAC9B,KAAK,CAAC,WAAW,EAAE,EAAE,EAAE,aAAa,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,qBAAqB,EAAE;gBACxB,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;YACtB,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,yBAAyB,EAAE;gBAC5B,KAAK,CAAC,YAAY,EAAE,EAAE,EAAE,cAAc,CAAC,CAAC;YAC1C,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,iCAAiC,EAAE;gBACpC,KAAK,CAAC,iBAAiB,EAAE,EAAE,EAAE,qBAAqB,CAAC,CAAC;YACtD,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,sCAAsC,EAAE;gBACzC,KAAK,CAAC,eAAe,EAAE,EAAE,EAAE,iBAAiB,CAAC,CAAC;YAChD,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,mCAAmC,EAAE;gBACtC,KAAK,CAAC,cAAc,EAAE,EAAE,EAAE,oBAAoB,CAAC,CAAC;YAClD,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,yCAAyC,EAAE;gBAC5C,KAAK,CAAC,eAAe,EAAE,EAAE,EAAE,qBAAqB,CAAC,CAAC;YACpD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,oBAAoB,EAAE;YAC7B,EAAE,CAAC,6BAA6B,EAAE;gBAChC,KAAK,CAAC,MAAM,EAAE,CAAC,WAAW,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,yBAAyB,CAAC,CAAC;YACnE,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,8BAA8B,EAAE;gBACjC,KAAK,CAAC,MAAM,EAAE,CAAC,uBAAuB,CAAC,EAAE,gCAAgC,CAAC,CAAC;YAC7E,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,qCAAqC,EAAE;gBACxC,KAAK,CAAC,MAAM,EAAE,CAAC,wBAAwB,CAAC,EAAE,mCAAmC,CAAC,CAAC;YACjF,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,kCAAkC,EAAE;gBACrC,KAAK,CAAC,MAAM,EAAE,CAAC,qBAAqB,CAAC,EAAE,gCAAgC,CAAC,CAAC;YAC3E,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,gCAAgC,EAAE;gBACnC,KAAK,CAAC,MAAM,EAAE,CAAC,mBAAmB,CAAC,EAAE,8BAA8B,CAAC,CAAC;YACvE,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,qBAAqB,EAAE;YAC9B,EAAE,CAAC,4BAA4B,EAAE;gBAC/B,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,wBAAwB,EAAE;gBAC3B,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,kBAAkB,CAAC,CAAC;gBACjD,KAAK,CAAC,MAAM,EAAE,iBAAiB,EAAE,sBAAsB,CAAC,CAAC;YAC3D,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,kBAAkB,EAAE;YAC3B,EAAE,CAAC,sBAAsB,EAAE;gBACzB,KAAK,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,2DAA2D,CAAC,EAAE,2EAA2E,CAAC,CAAC;YACrK,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,qBAAqB,EAAE;gBACxB,KAAK,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,8CAA8C,CAAC,EAAE,6DAA6D,CAAC,CAAC;YAC1I,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0f14f3d7c3441878cf7d775d0d4ff1ef96e593f9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,181 @@@
++"use strict";
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++var __extends = (this && this.__extends) || (function () {
++    var extendStatics = function (d, b) {
++        extendStatics = Object.setPrototypeOf ||
++            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
++            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
++        return extendStatics(d, b);
++    };
++    return function (d, b) {
++        extendStatics(d, b);
++        function __() { this.constructor = d; }
++        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
++    };
++})();
++Object.defineProperty(exports, "__esModule", { value: true });
++var terminal_1 = require("./terminal");
++var windowsPtyAgent_1 = require("./windowsPtyAgent");
++var utils_1 = require("./utils");
++var DEFAULT_FILE = 'cmd.exe';
++var DEFAULT_NAME = 'Windows Shell';
++var WindowsTerminal = /** @class */ (function (_super) {
++    __extends(WindowsTerminal, _super);
++    function WindowsTerminal(file, args, opt) {
++        var _this = _super.call(this, opt) || this;
++        // Initialize arguments
++        args = args || [];
++        file = file || DEFAULT_FILE;
++        opt = opt || {};
++        opt.env = opt.env || process.env;
++        if (opt.encoding) {
++            console.warn('Setting encoding on Windows is not supported');
++        }
++        var env = utils_1.assign({}, opt.env);
++        _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
++        _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
++        var cwd = opt.cwd || process.cwd();
++        var name = opt.name || env.TERM || DEFAULT_NAME;
++        var parsedEnv = _this._parseEnv(env);
++        // If the terminal is ready
++        _this._isReady = false;
++        // Functions that need to run after `ready` event is emitted.
++        _this._deferreds = [];
++        // Create new termal.
++        _this._agent = new windowsPtyAgent_1.WindowsPtyAgent(file, args, parsedEnv, cwd, _this._cols, _this._rows, false, opt.useConpty, opt.conptyInheritCursor);
++        _this._socket = _this._agent.outSocket;
++        // Not available until `ready` event emitted.
++        _this._pid = _this._agent.innerPid;
++        _this._fd = _this._agent.fd;
++        _this._pty = _this._agent.pty;
++        // The forked windows terminal is not available until `ready` event is
++        // emitted.
++        _this._socket.on('ready_datapipe', function () {
++            // These events needs to be forwarded.
++            ['connect', 'data', 'end', 'timeout', 'drain'].forEach(function (event) {
++                _this._socket.on(event, function () {
++                    // Wait until the first data event is fired then we can run deferreds.
++                    if (!_this._isReady && event === 'data') {
++                        // Terminal is now ready and we can avoid having to defer method
++                        // calls.
++                        _this._isReady = true;
++                        // Execute all deferred methods
++                        _this._deferreds.forEach(function (fn) {
++                            // NB! In order to ensure that `this` has all its references
++                            // updated any variable that need to be available in `this` before
++                            // the deferred is run has to be declared above this forEach
++                            // statement.
++                            fn.run();
++                        });
++                        // Reset
++                        _this._deferreds = [];
++                    }
++                });
++            });
++            // Shutdown if `error` event is emitted.
++            _this._socket.on('error', function (err) {
++                // Close terminal session.
++                _this._close();
++                // EIO, happens when someone closes our child process: the only process
++                // in the terminal.
++                // node < 0.6.14: errno 5
++                // node >= 0.6.14: read EIO
++                if (err.code) {
++                    if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO'))
++                        return;
++                }
++                // Throw anything else.
++                if (_this.listeners('error').length < 2) {
++                    throw err;
++                }
++            });
++            // Cleanup after the socket is closed.
++            _this._socket.on('close', function () {
++                _this.emit('exit', _this._agent.exitCode);
++                _this._close();
++            });
++        });
++        _this._file = file;
++        _this._name = name;
++        _this._readable = true;
++        _this._writable = true;
++        _this._forwardEvents();
++        return _this;
++    }
++    WindowsTerminal.prototype._write = function (data) {
++        this._defer(this._doWrite, data);
++    };
++    WindowsTerminal.prototype._doWrite = function (data) {
++        this._agent.inSocket.write(data);
++    };
++    /**
++     * openpty
++     */
++    WindowsTerminal.open = function (options) {
++        throw new Error('open() not supported on windows, use Fork() instead.');
++    };
++    /**
++     * TTY
++     */
++    WindowsTerminal.prototype.resize = function (cols, rows) {
++        var _this = this;
++        if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
++            throw new Error('resizing must be done using positive cols and rows');
++        }
++        this._defer(function () {
++            _this._agent.resize(cols, rows);
++            _this._cols = cols;
++            _this._rows = rows;
++        });
++    };
++    WindowsTerminal.prototype.destroy = function () {
++        var _this = this;
++        this._defer(function () {
++            _this.kill();
++        });
++    };
++    WindowsTerminal.prototype.kill = function (signal) {
++        var _this = this;
++        this._defer(function () {
++            if (signal) {
++                throw new Error('Signals not supported on windows.');
++            }
++            _this._close();
++            _this._agent.kill();
++        });
++    };
++    WindowsTerminal.prototype._defer = function (deferredFn, arg) {
++        var _this = this;
++        // If the terminal is ready, execute.
++        if (this._isReady) {
++            deferredFn.call(this, arg);
++            return;
++        }
++        // Queue until terminal is ready.
++        this._deferreds.push({
++            run: function () { return deferredFn.call(_this, arg); }
++        });
++    };
++    Object.defineProperty(WindowsTerminal.prototype, "process", {
++        get: function () { return this._name; },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(WindowsTerminal.prototype, "master", {
++        get: function () { throw new Error('master is not supported on Windows'); },
++        enumerable: true,
++        configurable: true
++    });
++    Object.defineProperty(WindowsTerminal.prototype, "slave", {
++        get: function () { throw new Error('slave is not supported on Windows'); },
++        enumerable: true,
++        configurable: true
++    });
++    return WindowsTerminal;
++}(terminal_1.Terminal));
++exports.WindowsTerminal = WindowsTerminal;
++//# sourceMappingURL=windowsTerminal.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..30b49af4d19121fb9f8ba11df1286834460e54b8
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"windowsTerminal.js","sourceRoot":"","sources":["../src/windowsTerminal.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;;;;;;;;;;AAGH,uCAAkE;AAClE,qDAAoD;AAGpD,iCAAiC;AAEjC,IAAM,YAAY,GAAG,SAAS,CAAC;AAC/B,IAAM,YAAY,GAAG,eAAe,CAAC;AAErC;IAAqC,mCAAQ;IAK3C,yBAAY,IAAa,EAAE,IAAwB,EAAE,GAA4B;QAAjF,YACE,kBAAM,GAAG,CAAC,SAmGX;QAjGC,uBAAuB;QACvB,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QAClB,IAAI,GAAG,IAAI,IAAI,YAAY,CAAC;QAC5B,GAAG,GAAG,GAAG,IAAI,EAAE,CAAC;QAChB,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC;QAEjC,IAAI,GAAG,CAAC,QAAQ,EAAE;YAChB,OAAO,CAAC,IAAI,CAAC,8CAA8C,CAAC,CAAC;SAC9D;QAED,IAAM,GAAG,GAAG,cAAM,CAAC,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;QAChC,KAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,IAAI,uBAAY,CAAC;QACtC,KAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,IAAI,uBAAY,CAAC;QACtC,IAAM,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;QACrC,IAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,YAAY,CAAC;QAClD,IAAM,SAAS,GAAG,KAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QAEtC,2BAA2B;QAC3B,KAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;QAEtB,6DAA6D;QAC7D,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QAErB,qBAAqB;QACrB,KAAI,CAAC,MAAM,GAAG,IAAI,iCAAe,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,KAAI,CAAC,KAAK,EAAE,KAAI,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACrI,KAAI,CAAC,OAAO,GAAG,KAAI,CAAC,MAAM,CAAC,SAAS,CAAC;QAErC,6CAA6C;QAC7C,KAAI,CAAC,IAAI,GAAG,KAAI,CAAC,MAAM,CAAC,QAAQ,CAAC;QACjC,KAAI,CAAC,GAAG,GAAG,KAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,KAAI,CAAC,IAAI,GAAG,KAAI,CAAC,MAAM,CAAC,GAAG,CAAC;QAE5B,sEAAsE;QACtE,WAAW;QACX,KAAI,CAAC,OAAO,CAAC,EAAE,CAAC,gBAAgB,EAAE;YAEhC,sCAAsC;YACtC,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,UAAA,KAAK;gBAC1D,KAAI,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE;oBAErB,sEAAsE;oBACtE,IAAI,CAAC,KAAI,CAAC,QAAQ,IAAI,KAAK,KAAK,MAAM,EAAE;wBAEtC,gEAAgE;wBAChE,SAAS;wBACT,KAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;wBAErB,+BAA+B;wBAC/B,KAAI,CAAC,UAAU,CAAC,OAAO,CAAC,UAAA,EAAE;4BACxB,4DAA4D;4BAC5D,kEAAkE;4BAClE,4DAA4D;4BAC5D,aAAa;4BACb,EAAE,CAAC,GAAG,EAAE,CAAC;wBACX,CAAC,CAAC,CAAC;wBAEH,QAAQ;wBACR,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;qBAEtB;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YAEH,wCAAwC;YACxC,KAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,UAAA,GAAG;gBAC1B,0BAA0B;gBAC1B,KAAI,CAAC,MAAM,EAAE,CAAC;gBAEd,uEAAuE;gBACvE,mBAAmB;gBACnB,yBAAyB;gBACzB,2BAA2B;gBAC3B,IAAU,GAAI,CAAC,IAAI,EAAE;oBACnB,IAAI,CAAO,GAAI,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAO,GAAI,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;wBAAE,OAAO;iBACpF;gBAED,uBAAuB;gBACvB,IAAI,KAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;oBACtC,MAAM,GAAG,CAAC;iBACX;YACH,CAAC,CAAC,CAAC;YAEH,sCAAsC;YACtC,KAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE;gBACvB,KAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBACxC,KAAI,CAAC,MAAM,EAAE,CAAC;YAChB,CAAC,CAAC,CAAC;QAEL,CAAC,CAAC,CAAC;QAEH,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAElB,KAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,KAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,KAAI,CAAC,cAAc,EAAE,CAAC;;IACxB,CAAC;IAES,gCAAM,GAAhB,UAAiB,IAAY;QAC3B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;IAEO,kCAAQ,GAAhB,UAAiB,IAAY;QAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED;;OAEG;IAEW,oBAAI,GAAlB,UAAmB,OAAyB;QAC1C,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IAED;;OAEG;IAEI,gCAAM,GAAb,UAAc,IAAY,EAAE,IAAY;QAAxC,iBASC;QARC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,QAAQ,EAAE;YAClG,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QACD,IAAI,CAAC,MAAM,CAAC;YACV,KAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC/B,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;YAClB,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACpB,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,iCAAO,GAAd;QAAA,iBAIC;QAHC,IAAI,CAAC,MAAM,CAAC;YACV,KAAI,CAAC,IAAI,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,8BAAI,GAAX,UAAY,MAAe;QAA3B,iBAQC;QAPC,IAAI,CAAC,MAAM,CAAC;YACV,IAAI,MAAM,EAAE;gBACV,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;aACtD;YACD,KAAI,CAAC,MAAM,EAAE,CAAC;YACd,KAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QACrB,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,gCAAM,GAAd,UAA8B,UAA6B,EAAE,GAAO;QAApE,iBAWC;QAVC,qCAAqC;QACrC,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YAC3B,OAAO;SACR;QAED,iCAAiC;QACjC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YACnB,GAAG,EAAE,cAAM,OAAA,UAAU,CAAC,IAAI,CAAC,KAAI,EAAE,GAAG,CAAC,EAA1B,CAA0B;SACtC,CAAC,CAAC;IACL,CAAC;IAED,sBAAW,oCAAO;aAAlB,cAA+B,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;;;OAAA;IACnD,sBAAW,mCAAM;aAAjB,cAA8B,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC,CAAC,CAAC;;;OAAA;IACtF,sBAAW,kCAAK;aAAhB,cAA6B,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC,CAAC,CAAC;;;OAAA;IACtF,sBAAC;AAAD,CAAC,AA1KD,CAAqC,mBAAQ,GA0K5C;AA1KY,0CAAe"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1a638e49636348e425d3476c37d63667fa0371b6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,195 @@@
++"use strict";
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++Object.defineProperty(exports, "__esModule", { value: true });
++var fs = require("fs");
++var assert = require("assert");
++var windowsTerminal_1 = require("./windowsTerminal");
++var path = require("path");
++var psList = require("ps-list");
++function pollForProcessState(desiredState, intervalMs, timeoutMs) {
++    if (intervalMs === void 0) { intervalMs = 100; }
++    if (timeoutMs === void 0) { timeoutMs = 2000; }
++    return new Promise(function (resolve) {
++        var tries = 0;
++        var interval = setInterval(function () {
++            psList({ all: true }).then(function (ps) {
++                var success = true;
++                var pids = Object.keys(desiredState).map(function (k) { return parseInt(k, 10); });
++                pids.forEach(function (pid) {
++                    if (desiredState[pid]) {
++                        if (!ps.some(function (p) { return p.pid === pid; })) {
++                            success = false;
++                        }
++                    }
++                    else {
++                        if (ps.some(function (p) { return p.pid === pid; })) {
++                            success = false;
++                        }
++                    }
++                });
++                if (success) {
++                    clearInterval(interval);
++                    resolve();
++                    return;
++                }
++                tries++;
++                if (tries * intervalMs >= timeoutMs) {
++                    clearInterval(interval);
++                    var processListing = pids.map(function (k) { return k + ": " + desiredState[k]; }).join('\n');
++                    assert.fail("Bad process state, expected:\n" + processListing);
++                    resolve();
++                }
++            });
++        }, intervalMs);
++    });
++}
++function pollForProcessTreeSize(pid, size, intervalMs, timeoutMs) {
++    if (intervalMs === void 0) { intervalMs = 100; }
++    if (timeoutMs === void 0) { timeoutMs = 2000; }
++    return new Promise(function (resolve) {
++        var tries = 0;
++        var interval = setInterval(function () {
++            psList({ all: true }).then(function (ps) {
++                var openList = [];
++                openList.push(ps.filter(function (p) { return p.pid === pid; }).map(function (p) {
++                    return { name: p.name, pid: p.pid };
++                })[0]);
++                var list = [];
++                var _loop_1 = function () {
++                    var current = openList.shift();
++                    ps.filter(function (p) { return p.ppid === current.pid; }).map(function (p) {
++                        return { name: p.name, pid: p.pid };
++                    }).forEach(function (p) { return openList.push(p); });
++                    list.push(current);
++                };
++                while (openList.length) {
++                    _loop_1();
++                }
++                var success = list.length === size;
++                if (success) {
++                    clearInterval(interval);
++                    resolve(list);
++                    return;
++                }
++                tries++;
++                if (tries * intervalMs >= timeoutMs) {
++                    clearInterval(interval);
++                    assert.fail("Bad process state, expected: " + size + ", actual: " + list.length);
++                    resolve();
++                }
++            });
++        }, intervalMs);
++    });
++}
++if (process.platform === 'win32') {
++    describe('WindowsTerminal', function () {
++        describe('kill', function () {
++            it('should not crash parent process', function (done) {
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
++                term.kill();
++                // Add done call to deferred function queue to ensure the kill call has completed
++                term._defer(done);
++            });
++            it('should kill the process tree', function (done) {
++                this.timeout(5000);
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
++                // Start sub-processes
++                term.write('powershell.exe\r');
++                term.write('notepad.exe\r');
++                term.write('node.exe\r');
++                pollForProcessTreeSize(term.pid, 4, 500, 5000).then(function (list) {
++                    assert.equal(list[0].name, 'cmd.exe');
++                    assert.equal(list[1].name, 'powershell.exe');
++                    assert.equal(list[2].name, 'notepad.exe');
++                    assert.equal(list[3].name, 'node.exe');
++                    term.kill();
++                    var desiredState = {};
++                    desiredState[list[0].pid] = false;
++                    desiredState[list[1].pid] = false;
++                    desiredState[list[2].pid] = true;
++                    desiredState[list[3].pid] = false;
++                    pollForProcessState(desiredState).then(function () {
++                        // Kill notepad before done
++                        process.kill(list[2].pid);
++                        done();
++                    });
++                });
++            });
++        });
++        describe('resize', function () {
++            it('should throw a non-native exception when resizing an invalid value', function () {
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
++                assert.throws(function () { return term.resize(-1, -1); });
++                assert.throws(function () { return term.resize(0, 0); });
++                assert.doesNotThrow(function () { return term.resize(1, 1); });
++            });
++            it('should throw an non-native exception when resizing a killed terminal', function (done) {
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
++                term._defer(function () {
++                    term.on('exit', function () {
++                        assert.throws(function () { return term.resize(1, 1); });
++                        done();
++                    });
++                    term.destroy();
++                });
++            });
++        });
++        describe('Args as CommandLine', function () {
++            it('should not fail running a file containing a space in the path', function (done) {
++                var spaceFolder = path.resolve(__dirname, '..', 'fixtures', 'space folder');
++                if (!fs.existsSync(spaceFolder)) {
++                    fs.mkdirSync(spaceFolder);
++                }
++                var cmdCopiedPath = path.resolve(spaceFolder, 'cmd.exe');
++                var data = fs.readFileSync(process.env.windir + "\\System32\\cmd.exe");
++                fs.writeFileSync(cmdCopiedPath, data);
++                if (!fs.existsSync(cmdCopiedPath)) {
++                    // Skip test if git bash isn't installed
++                    return;
++                }
++                var term = new windowsTerminal_1.WindowsTerminal(cmdCopiedPath, '/c echo "hello world"', {});
++                var result = '';
++                term.on('data', function (data) {
++                    result += data;
++                });
++                term.on('exit', function () {
++                    assert.ok(result.indexOf('hello world') >= 1);
++                    done();
++                });
++            });
++        });
++        describe('env', function () {
++            it('should set environment variables of the shell', function (done) {
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', '/C echo %FOO%', { env: { FOO: 'BAR' } });
++                var result = '';
++                term.on('data', function (data) {
++                    result += data;
++                });
++                term.on('exit', function () {
++                    assert.ok(result.indexOf('BAR') >= 0);
++                    done();
++                });
++            });
++        });
++        describe('On close', function () {
++            it('should return process zero exit codes', function (done) {
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', '/C exit');
++                term.on('exit', function (code) {
++                    assert.equal(code, 0);
++                    done();
++                });
++            });
++            it('should return process non-zero exit codes', function (done) {
++                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', '/C exit 2');
++                term.on('exit', function (code) {
++                    assert.equal(code, 2);
++                    done();
++                });
++            });
++        });
++    });
++}
++//# sourceMappingURL=windowsTerminal.test.js.map
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6eaac58fc3de8f605cbd5d8cb1ae24dd2033de03
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++{"version":3,"file":"windowsTerminal.test.js","sourceRoot":"","sources":["../src/windowsTerminal.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,uBAAyB;AACzB,+BAAiC;AACjC,qDAAoD;AACpD,2BAA6B;AAC7B,gCAAkC;AAYlC,SAAS,mBAAmB,CAAC,YAA2B,EAAE,UAAwB,EAAE,SAAwB;IAAlD,2BAAA,EAAA,gBAAwB;IAAE,0BAAA,EAAA,gBAAwB;IAC1G,OAAO,IAAI,OAAO,CAAO,UAAA,OAAO;QAC9B,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAM,QAAQ,GAAG,WAAW,CAAC;YAC3B,MAAM,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,UAAA,EAAE;gBAC3B,IAAI,OAAO,GAAG,IAAI,CAAC;gBACnB,IAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,EAAf,CAAe,CAAC,CAAC;gBACjE,IAAI,CAAC,OAAO,CAAC,UAAA,GAAG;oBACd,IAAI,YAAY,CAAC,GAAG,CAAC,EAAE;wBACrB,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,GAAG,KAAK,GAAG,EAAb,CAAa,CAAC,EAAE;4BAChC,OAAO,GAAG,KAAK,CAAC;yBACjB;qBACF;yBAAM;wBACL,IAAI,EAAE,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,GAAG,KAAK,GAAG,EAAb,CAAa,CAAC,EAAE;4BAC/B,OAAO,GAAG,KAAK,CAAC;yBACjB;qBACF;gBACH,CAAC,CAAC,CAAC;gBACH,IAAI,OAAO,EAAE;oBACX,aAAa,CAAC,QAAQ,CAAC,CAAC;oBACxB,OAAO,EAAE,CAAC;oBACV,OAAO;iBACR;gBACD,KAAK,EAAE,CAAC;gBACR,IAAI,KAAK,GAAG,UAAU,IAAI,SAAS,EAAE;oBACnC,aAAa,CAAC,QAAQ,CAAC,CAAC;oBACxB,IAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAG,CAAC,UAAK,YAAY,CAAC,CAAC,CAAG,EAA1B,CAA0B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;oBAC5E,MAAM,CAAC,IAAI,CAAC,mCAAiC,cAAgB,CAAC,CAAC;oBAC/D,OAAO,EAAE,CAAC;iBACX;YACH,CAAC,CAAC,CAAC;QACL,CAAC,EAAE,UAAU,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAAC,GAAW,EAAE,IAAY,EAAE,UAAwB,EAAE,SAAwB;IAAlD,2BAAA,EAAA,gBAAwB;IAAE,0BAAA,EAAA,gBAAwB;IAC3G,OAAO,IAAI,OAAO,CAA8B,UAAA,OAAO;QACrD,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAM,QAAQ,GAAG,WAAW,CAAC;YAC3B,MAAM,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,UAAA,EAAE;gBAC3B,IAAM,QAAQ,GAAgC,EAAE,CAAC;gBACjD,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,GAAG,KAAK,GAAG,EAAb,CAAa,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC;oBAC/C,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC;gBACtC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBACP,IAAM,IAAI,GAAgC,EAAE,CAAC;;oBAE3C,IAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;oBACjC,EAAE,CAAC,MAAM,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,GAAG,EAAtB,CAAsB,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC;wBAC1C,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC;oBACtC,CAAC,CAAC,CAAC,OAAO,CAAC,UAAA,CAAC,IAAI,OAAA,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAhB,CAAgB,CAAC,CAAC;oBAClC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;;gBALrB,OAAO,QAAQ,CAAC,MAAM;;iBAMrB;gBACD,IAAM,OAAO,GAAG,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC;gBACrC,IAAI,OAAO,EAAE;oBACX,aAAa,CAAC,QAAQ,CAAC,CAAC;oBACxB,OAAO,CAAC,IAAI,CAAC,CAAC;oBACd,OAAO;iBACR;gBACD,KAAK,EAAE,CAAC;gBACR,IAAI,KAAK,GAAG,UAAU,IAAI,SAAS,EAAE;oBACnC,aAAa,CAAC,QAAQ,CAAC,CAAC;oBACxB,MAAM,CAAC,IAAI,CAAC,kCAAgC,IAAI,kBAAa,IAAI,CAAC,MAAQ,CAAC,CAAC;oBAC5E,OAAO,EAAE,CAAC;iBACX;YACH,CAAC,CAAC,CAAC;QACL,CAAC,EAAE,UAAU,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,QAAQ,CAAC,iBAAiB,EAAE;QAC1B,QAAQ,CAAC,MAAM,EAAE;YACf,EAAE,CAAC,iCAAiC,EAAE,UAAC,IAAI;gBACzC,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;gBACpD,IAAI,CAAC,IAAI,EAAE,CAAC;gBACZ,iFAAiF;gBAC3E,IAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YAC3B,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,8BAA8B,EAAE,UAAU,IAAgB;gBAC3D,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;gBACnB,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;gBACpD,sBAAsB;gBACtB,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;gBAC/B,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;gBAC5B,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;gBACzB,sBAAsB,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,UAAA,IAAI;oBACtD,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;oBACtC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;oBAC7C,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;oBAC1C,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;oBACvC,IAAI,CAAC,IAAI,EAAE,CAAC;oBACZ,IAAM,YAAY,GAAkB,EAAE,CAAC;oBACvC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;oBAClC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;oBAClC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;oBACjC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;oBAClC,mBAAmB,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC;wBACrC,2BAA2B;wBAC3B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;wBAC1B,IAAI,EAAE,CAAC;oBACT,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,QAAQ,EAAE;YACjB,EAAE,CAAC,oEAAoE,EAAE;gBACvE,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;gBACpD,MAAM,CAAC,MAAM,CAAC,cAAM,OAAA,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAnB,CAAmB,CAAC,CAAC;gBACzC,MAAM,CAAC,MAAM,CAAC,cAAM,OAAA,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAjB,CAAiB,CAAC,CAAC;gBACvC,MAAM,CAAC,YAAY,CAAC,cAAM,OAAA,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAjB,CAAiB,CAAC,CAAC;YAC/C,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,sEAAsE,EAAE,UAAC,IAAI;gBAC9E,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;gBAC9C,IAAK,CAAC,MAAM,CAAC;oBACjB,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;wBACd,MAAM,CAAC,MAAM,CAAC,cAAM,OAAA,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAjB,CAAiB,CAAC,CAAC;wBACvC,IAAI,EAAE,CAAC;oBACT,CAAC,CAAC,CAAC;oBACH,IAAI,CAAC,OAAO,EAAE,CAAC;gBACjB,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,qBAAqB,EAAE;YAC9B,EAAE,CAAC,+DAA+D,EAAE,UAAC,IAAI;gBACvE,IAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;gBAC9E,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE;oBAC/B,EAAE,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;iBAC3B;gBAED,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;gBAC3D,IAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAI,OAAO,CAAC,GAAG,CAAC,MAAM,wBAAqB,CAAC,CAAC;gBACzE,EAAE,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;gBAEtC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE;oBACjC,wCAAwC;oBACxC,OAAO;iBACR;gBACD,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,aAAa,EAAE,uBAAuB,EAAE,EAAE,CAAC,CAAC;gBAC7E,IAAI,MAAM,GAAG,EAAE,CAAC;gBAChB,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,IAAI,IAAI,CAAC;gBACjB,CAAC,CAAC,CAAC;gBACH,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;oBACd,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;oBAC9C,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,KAAK,EAAE;YACd,EAAE,CAAC,+CAA+C,EAAE,UAAC,IAAI;gBACvD,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,eAAe,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,EAAC,CAAC,CAAC;gBACrF,IAAI,MAAM,GAAG,EAAE,CAAC;gBAChB,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,IAAI,IAAI,CAAC;gBACjB,CAAC,CAAC,CAAC;gBACH,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;oBACd,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;oBACtC,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,UAAU,EAAE;YACnB,EAAE,CAAC,uCAAuC,EAAE,UAAC,IAAI;gBAC/C,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;gBACvD,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;oBACtB,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YAEH,EAAE,CAAC,2CAA2C,EAAE,UAAC,IAAI;gBACnD,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;gBACzD,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;oBACtB,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ"}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7cdfbe77de38309f80a7780b6036044846a85275
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,529 @@@
++# NAN ChangeLog
++
++**Version 2.14.0: current Node 12.2.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1**
++
++### 2.14.0 May 16 2019
++
++  - Feature: Add missing methods to Nan::Maybe<T> (#852) 4e962489fb84a184035b9fa74f245f650249aca6
++
++### 2.13.2 Mar 24 2019
++
++  - Bugfix: remove usage of deprecated `IsNearDeath` (#842) fbaf42252af279c3d867c6b193571f9711c39847
++
++### 2.13.1 Mar 14 2019
++
++  - Bugfix: check V8 version directly instead of inferring from NMV (#840) 12f9df9f393285de8fb4a8cd01478dc4fe3b089d
++
++### 2.13.0 Mar 13 2019
++
++  - Feature: add support for node master (#831) 113c0282072e7ff4f9dfc98b432fd894b798c2c
++
++### 2.12.1 Dec 18 2018
++
++  - Bugfix: Fix build breakage with Node.js 10.0.0-10.9.0. (#833) 625e90e8fef8d39ffa7247250a76a100b2487474
++
++### 2.12.0 Dec 16 2018
++
++  - Bugfix: Add scope.Escape() to Call() (#817) 2e5ed4fc3a8ac80a6ef1f2a55099ab3ac8800dc6
++  - Bugfix: Fix Node.js v10.12.0 deprecation warnings. 509859cc23b1770376b56550a027840a2ce0f73d
++  - Feature: Allow SetWeak() for non-object persistent handles. (#824) e6ef6a48e7e671fe3e4b7dddaa8912a3f8262ecd
++
++### 2.11.1 Sep 29 2018
++
++  - Fix: adapt to V8 7.0 24a22c3b25eeeec2016c6ec239bdd6169e985447
++
++### 2.11.0 Aug 25 2018
++
++  - Removal: remove `FunctionCallbackInfo::Callee` for nodejs `>= 10` 1a56c0a6efd4fac944cb46c30912a8e023bda7d4
++  - Bugfix: Fix `AsyncProgressWorkerBase::WorkProgress` sends invalid data b0c764d1dab11e9f8b37ffb81e2560a4498aad5e
++  - Feature: Introduce `GetCurrentEventLoop` b4911b0bb1f6d47d860e10ec014d941c51efac5e
++  - Feature: Add `NAN_MODULE_WORKER_ENABLED` macro as a replacement for `NAN_MODULE` b058fb047d18a58250e66ae831444441c1f2ac7a
++
++### 2.10.0 Mar 16 2018
++
++  - Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950
++  - Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452
++  - Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b
++  - Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a
++
++### 2.9.2 Feb 22 2018
++
++  - Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b
++
++### 2.9.1 Feb 22 2018
++
++  - Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4
++  - Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2
++
++### 2.9.0 Feb 22 2018
++
++  - Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309
++  - Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o
++  - Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee
++  - Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4
++  - Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606
++  - Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c
++  - Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b
++
++### 2.8.0 Nov 15 2017
++
++  - Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
++  - Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb
++  - Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
++  - Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900
++  - Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
++
++### 2.7.0 Aug 30 2017
++
++  - Feature: Add `Nan::To<v8::Function>()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b
++  - Bugfix: Fix ternary in `Nan::MaybeLocal<T>::FromMaybe<S>()`. 79a26f7d362e756a9524e672a82c3d603b542867
++
++### 2.6.2 Apr 12 2017
++
++  - Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d
++
++### 2.6.1 Apr 6 2017
++
++  - Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51
++
++### 2.6.0 Apr 6 2017
++
++  - Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5
++
++### 2.5.1 Jan 23 2017
++
++  - Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0
++  - Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112
++  - Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50
++
++### 2.5.0 Dec 21 2016
++
++  - Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178
++  - Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018
++
++### 2.4.0 Jul 10 2016
++
++  - Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649
++  - Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0
++  - Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2
++
++### 2.3.5 May 31 2016
++
++  - Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909
++
++### 2.3.4 May 31 2016
++
++  - Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9
++  - Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246
++  - Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc
++  - Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8
++
++### 2.3.3 May 4 2016
++
++  - Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8
++
++### 2.3.2 Apr 27 2016
++
++  - Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52
++
++### 2.3.1 Apr 27 2016
++
++  - Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e
++
++### 2.3.0 Apr 27 2016
++
++  - Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38
++  - Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece
++
++### 2.2.1 Mar 29 2016
++
++  - Bugfix: Use NewFromUnsigned in ReturnValue<T>::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58
++  - Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9
++
++### 2.2.0 Jan 9 2016
++
++  - Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6
++  - Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec
++  - Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9
++  - Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b
++
++### 2.1.0 Oct 8 2015
++
++  - Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c
++  - Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555
++  - Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d
++  - Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b
++  - Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537
++  - Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff
++  - Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f
++
++### 2.0.9 Sep 8 2015
++
++  - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7
++
++### 2.0.8 Aug 28 2015
++
++  - Work around duplicate linking bug in clang 11902da
++
++### 2.0.7 Aug 26 2015
++
++  - Build: Repackage
++
++### 2.0.6 Aug 26 2015
++
++  - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1
++  - Bugfix: Remove unused static std::map instances 525bddc
++  - Bugfix: Make better use of maybe versions of APIs bfba85b
++  - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d
++
++### 2.0.5 Aug 10 2015
++
++  - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1
++  - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d
++
++### 2.0.4 Aug 6 2015
++
++  - Build: Repackage
++
++### 2.0.3 Aug 6 2015
++
++  - Bugfix: Don't use clang++ / g++ syntax extension. 231450e
++
++### 2.0.2 Aug 6 2015
++
++  - Build: Repackage
++
++### 2.0.1 Aug 6 2015
++
++  - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687
++  - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601
++  - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f
++  - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed
++
++### 2.0.0 Jul 31 2015
++
++  - Change: Renamed identifiers with leading underscores      b5932b4
++  - Change: Replaced NanObjectWrapHandle with class NanObjectWrap     464f1e1
++  - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4
++  - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99
++  - Change: Rename NanBufferUse to NanNewBuffer       3e8b0a5
++  - Change: Rename NanNewBuffer to NanCopyBuffer      d6af78d
++  - Change: Remove Nan prefix from all names  72d1f67
++  - Change: Update Buffer API for new upstream changes        d5d3291
++  - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope   21a7a6a
++  - Change: Get rid of Handles         e6c0daf
++  - Feature: Support io.js 3 with V8 4.4
++  - Feature: Introduce NanPersistent  7fed696
++  - Feature: Introduce NanGlobal      4408da1
++  - Feature: Added NanTryCatch        10f1ca4
++  - Feature: Update for V8 v4.3       4b6404a
++  - Feature: Introduce NanNewOneByteString    c543d32
++  - Feature: Introduce namespace Nan  67ed1b1
++  - Removal: Remove NanLocker and NanUnlocker dd6e401
++  - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9
++  - Removal: Remove NanReturn* macros d90a25c
++  - Removal: Remove HasInstance       e8f84fe
++
++
++### 1.9.0 Jul 31 2015
++
++  - Feature: Added `NanFatalException` 81d4a2c
++  - Feature: Added more error types 4265f06
++  - Feature: Added dereference and function call operators to NanCallback c4b2ed0
++  - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c
++  - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6
++  - Feature: Added NanErrnoException dd87d9e
++  - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130
++  - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c
++  - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b
++
++### 1.8.4 Apr 26 2015
++
++  - Build: Repackage
++
++### 1.8.3 Apr 26 2015
++
++  - Bugfix: Include missing header 1af8648
++
++### 1.8.2 Apr 23 2015
++
++  - Build: Repackage
++
++### 1.8.1 Apr 23 2015
++
++  - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3
++
++### 1.8.0 Apr 23 2015
++
++  - Feature: Allow primitives with NanReturnValue 2e4475e
++  - Feature: Added comparison operators to NanCallback 55b075e
++  - Feature: Backport thread local storage 15bb7fa
++  - Removal: Remove support for signatures with arguments 8a2069d
++  - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59
++
++### 1.7.0 Feb 28 2015
++
++  - Feature: Made NanCallback::Call accept optional target 8d54da7
++  - Feature: Support atom-shell 0.21 0b7f1bb
++
++### 1.6.2 Feb 6 2015
++
++  - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639
++
++### 1.6.1 Jan 23 2015
++
++  - Build: version bump
++
++### 1.5.3 Jan 23 2015
++
++  - Build: repackage
++
++### 1.6.0 Jan 23 2015
++
++ - Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af
++ - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179
++ - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9
++
++### 1.5.2 Jan 23 2015
++
++  - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4
++  - Bugfix: Readded missing String constructors 18d828f
++  - Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b
++  - Bugfix: Fix uv_work_cb versioning 997e4ae
++  - Bugfix: Add function factory and test 4eca89c
++  - Bugfix: Add object template factory and test cdcb951
++  - Correctness: Lifted an io.js related typedef c9490be
++  - Correctness: Make explicit downcasts of String lengths 00074e6
++  - Windows: Limit the scope of disabled warning C4530 83d7deb
++
++### 1.5.1 Jan 15 2015
++
++  - Build: version bump
++
++### 1.4.3 Jan 15 2015
++
++  - Build: version bump
++
++### 1.4.2 Jan 15 2015
++
++  - Feature: Support io.js 0dbc5e8
++
++### 1.5.0 Jan 14 2015
++
++ - Feature: Support io.js b003843
++ - Correctness: Improved NanNew internals 9cd4f6a
++ - Feature: Implement progress to NanAsyncWorker 8d6a160
++
++### 1.4.1 Nov 8 2014
++
++ - Bugfix: Handle DEBUG definition correctly
++ - Bugfix: Accept int as Boolean
++
++### 1.4.0 Nov 1 2014
++
++ - Feature: Added NAN_GC_CALLBACK 6a5c245
++ - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8
++ - Correctness: Added constness to references in NanHasInstance 02c61cd
++ - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6
++ - Windoze: Shut Visual Studio up when compiling 8d558c1
++ - License: Switch to plain MIT from custom hacked MIT license 11de983
++ - Build: Added test target to Makefile e232e46
++ - Performance: Removed superfluous scope in NanAsyncWorker f4b7821
++ - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208
++ - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450
++
++### 1.3.0 Aug 2 2014
++
++ - Added NanNew<v8::String, std::string>(std::string)
++ - Added NanNew<v8::String, std::string&>(std::string&)
++ - Added NanAsciiString helper class
++ - Added NanUtf8String helper class
++ - Added NanUcs2String helper class
++ - Deprecated NanRawString()
++ - Deprecated NanCString()
++ - Added NanGetIsolateData(v8::Isolate *isolate)
++ - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv)
++ - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv)
++ - Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv)
++ - Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
++ - Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
++ - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value)
++ - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
++
++### 1.2.0 Jun 5 2014
++
++ - Add NanSetPrototypeTemplate
++ - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class,
++     introduced _NanWeakCallbackDispatcher
++ - Removed -Wno-unused-local-typedefs from test builds
++ - Made test builds Windows compatible ('Sleep()')
++
++### 1.1.2 May 28 2014
++
++ - Release to fix more stuff-ups in 1.1.1
++
++### 1.1.1 May 28 2014
++
++ - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0
++
++### 1.1.0 May 25 2014
++
++ - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead
++ - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]),
++     (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*,
++     v8::String::ExternalAsciiStringResource*
++ - Deprecate NanSymbol()
++ - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker
++
++### 1.0.0 May 4 2014
++
++ - Heavy API changes for V8 3.25 / Node 0.11.13
++ - Use cpplint.py
++ - Removed NanInitPersistent
++ - Removed NanPersistentToLocal
++ - Removed NanFromV8String
++ - Removed NanMakeWeak
++ - Removed NanNewLocal
++ - Removed NAN_WEAK_CALLBACK_OBJECT
++ - Removed NAN_WEAK_CALLBACK_DATA
++ - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions
++ - Introduce NanUndefined, NanNull, NanTrue and NanFalse
++ - Introduce NanEscapableScope and NanEscapeScope
++ - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node)
++ - Introduce NanMakeCallback for node::MakeCallback
++ - Introduce NanSetTemplate
++ - Introduce NanGetCurrentContext
++ - Introduce NanCompileScript and NanRunScript
++ - Introduce NanAdjustExternalMemory
++ - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback
++ - Introduce NanGetHeapStatistics
++ - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent()
++
++### 0.8.0 Jan 9 2014
++
++ - NanDispose -> NanDisposePersistent, deprecate NanDispose
++ - Extract _NAN_*_RETURN_TYPE, pull up NAN_*()
++
++### 0.7.1 Jan 9 2014
++
++ - Fixes to work against debug builds of Node
++ - Safer NanPersistentToLocal (avoid reinterpret_cast)
++ - Speed up common NanRawString case by only extracting flattened string when necessary
++
++### 0.7.0 Dec 17 2013
++
++ - New no-arg form of NanCallback() constructor.
++ - NanCallback#Call takes Handle rather than Local
++ - Removed deprecated NanCallback#Run method, use NanCallback#Call instead
++ - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS
++ - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call()
++ - Introduce NanRawString() for char* (or appropriate void*) from v8::String
++     (replacement for NanFromV8String)
++ - Introduce NanCString() for null-terminated char* from v8::String
++
++### 0.6.0 Nov 21 2013
++
++ - Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of
++     v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9
++
++### 0.5.2 Nov 16 2013
++
++ - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public
++
++### 0.5.1 Nov 12 2013
++
++ - Use node::MakeCallback() instead of direct v8::Function::Call()
++
++### 0.5.0 Nov 11 2013
++
++ - Added @TooTallNate as collaborator
++ - New, much simpler, "include_dirs" for binding.gyp
++ - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros
++
++### 0.4.4 Nov 2 2013
++
++ - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+
++
++### 0.4.3 Nov 2 2013
++
++ - Include node_object_wrap.h, removed from node.h for Node 0.11.8.
++
++### 0.4.2 Nov 2 2013
++
++ - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for
++     Node 0.11.8 release.
++
++### 0.4.1 Sep 16 2013
++
++ - Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8
++
++### 0.4.0 Sep 2 2013
++
++ - Added NAN_INLINE and NAN_DEPRECATED and made use of them
++ - Added NanError, NanTypeError and NanRangeError
++ - Cleaned up code
++
++### 0.3.2 Aug 30 2013
++
++ - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent
++     in NanAsyncWorker
++
++### 0.3.1 Aug 20 2013
++
++ - fix "not all control paths return a value" compile warning on some platforms
++
++### 0.3.0 Aug 19 2013
++
++ - Made NAN work with NPM
++ - Lots of fixes to NanFromV8String, pulling in features from new Node core
++ - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API
++ - Added optional error number argument for NanThrowError()
++ - Added NanInitPersistent()
++ - Added NanReturnNull() and NanReturnEmptyString()
++ - Added NanLocker and NanUnlocker
++ - Added missing scopes
++ - Made sure to clear disposed Persistent handles
++ - Changed NanAsyncWorker to allocate error messages on the heap
++ - Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>)
++ - Fixed leak in NanAsyncWorker when errmsg is used
++
++### 0.2.2 Aug 5 2013
++
++ - Fixed usage of undefined variable with node::BASE64 in NanFromV8String()
++
++### 0.2.1 Aug 5 2013
++
++ - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for
++     NanFromV8String()
++
++### 0.2.0 Aug 5 2013
++
++ - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR,
++     NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY
++ - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS,
++     _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS,
++     _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS,
++     _NAN_PROPERTY_QUERY_ARGS
++ - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer
++ - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT,
++     NAN_WEAK_CALLBACK_DATA, NanMakeWeak
++ - Renamed THROW_ERROR to _NAN_THROW_ERROR
++ - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*)
++ - Added NanBufferUse(char*, uint32_t)
++ - Added NanNewContextHandle(v8::ExtensionConfiguration*,
++       v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>)
++ - Fixed broken NanCallback#GetFunction()
++ - Added optional encoding and size arguments to NanFromV8String()
++ - Added NanGetPointerSafe() and NanSetPointerSafe()
++ - Added initial test suite (to be expanded)
++ - Allow NanUInt32OptionValue to convert any Number object
++
++### 0.1.0 Jul 21 2013
++
++ - Added `NAN_GETTER`, `NAN_SETTER`
++ - Added `NanThrowError` with single Local<Value> argument
++ - Added `NanNewBufferHandle` with single uint32_t argument
++ - Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)`
++ - Added `Local<Function> NanCallback#GetFunction()`
++ - Added `NanCallback#Call(int, Local<Value>[])`
++ - Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..dddd13d5c1ddf8513fbfefe445e482ef2b16cbc2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,13 @@@
++The MIT License (MIT)
++=====================
++
++Copyright (c) 2018 NAN contributors
++-----------------------------------
++
++*NAN contributors listed at <https://github.com/nodejs/nan#contributors>*
++
++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
++
++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3389ef529d0e7d9f8a50d837dad1884338c41079
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,456 @@@
++Native Abstractions for Node.js
++===============================
++
++**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 and 12.**
++
++***Current version: 2.14.0***
++
++*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
++
++[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/)
++
++[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](https://travis-ci.org/nodejs/nan)
++[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan)
++
++Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
++
++This project also contains some helper utilities that make addon development a bit more pleasant.
++
++ * **[News & Updates](#news)**
++ * **[Usage](#usage)**
++ * **[Example](#example)**
++ * **[API](#api)**
++ * **[Tests](#tests)**
++ * **[Known issues](#issues)**
++ * **[Governance & Contributing](#governance)**
++
++<a name="news"></a>
++
++## News & Updates
++
++<a name="usage"></a>
++
++## Usage
++
++Simply add **NAN** as a dependency in the *package.json* of your Node addon:
++
++``` bash
++$ npm install --save nan
++```
++
++Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
++
++``` python
++"include_dirs" : [
++    "<!(node -e \"require('nan')\")"
++]
++```
++
++This works like a `-I<path-to-NAN>` when compiling your addon.
++
++<a name="example"></a>
++
++## Example
++
++Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**.
++
++Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
++
++For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
++
++Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
++
++Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure.
++
++<a name="api"></a>
++
++## API
++
++Additional to the NAN documentation below, please consult:
++
++* [The V8 Getting Started * Guide](https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding)
++* [The V8 Embedders * Guide](https://github.com/v8/v8/wiki/Embedder%27s%20Guide)
++* [V8 API Documentation](https://v8docs.nodesource.com/)
++* [Node Add-on Documentation](https://nodejs.org/api/addons.html)
++
++<!-- START API -->
++
++### JavaScript-accessible methods
++
++A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
++
++In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
++
++* **Method argument types**
++ - <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
++ - <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
++ - <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
++* **Method declarations**
++ - <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
++ - <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
++ - <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
++ - <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
++ - <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
++ - <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
++* Method and template helpers
++ - <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
++ - <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
++
++### Scopes
++
++A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
++
++A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
++
++The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
++
++ - <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
++ - <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
++
++Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
++
++### Persistent references
++
++An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
++
++Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
++
++ - <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
++ - <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
++ - <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
++ - <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
++ - <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
++ - <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
++ - <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
++
++Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
++
++### New
++
++NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
++
++ - <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
++ - <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
++ - <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
++ - <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
++ - <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
++ - <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
++
++
++### Converters
++
++NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
++
++ - <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
++
++### Maybe Types
++
++The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
++
++* **Maybe Types**
++  - <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
++* **Maybe Helpers**
++  - <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
++  - <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
++  - <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
++
++### Script
++
++NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
++
++ - <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
++ - <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
++
++
++### JSON
++
++The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
++
++ - <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
++ - <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
++
++Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
++
++### Errors
++
++NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
++
++Note that an Error object is simply a specialized form of `v8::Value`.
++
++Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
++
++ - <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
++ - <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
++ - <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
++ - <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
++ - <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
++
++
++### Buffers
++
++NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
++
++ - <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
++ - <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
++ - <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
++
++### Nan::Callback
++
++`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
++
++ - <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
++
++### Asynchronous work helpers
++
++`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
++
++ - <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
++ - <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
++ - <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
++ - <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
++
++### Strings & Bytes
++
++Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
++
++ - <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
++ - <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
++ - <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
++ - <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
++
++
++### Object Wrappers
++
++The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
++
++ - <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
++
++
++### V8 internals
++
++The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
++
++ - <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
++ - <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
++
++
++### Miscellaneous V8 Helpers
++
++ - <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
++ - <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
++ - <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
++ - <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
++ - <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
++
++
++### Miscellaneous Node Helpers
++
++ - <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
++ - <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
++ - <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
++ - <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
++
++<!-- END API -->
++
++
++<a name="tests"></a>
++
++### Tests
++
++To run the NAN tests do:
++
++``` sh
++npm install
++npm run-script rebuild-tests
++npm test
++```
++
++Or just:
++
++``` sh
++npm install
++make test
++```
++
++<a name="issues"></a>
++
++## Known issues
++
++### Compiling against Node.js 0.12 on OSX
++
++With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12
++do not compile anymore. The error looks something like:
++
++```
++❯   CXX(target) Release/obj.target/accessors/cpp/accessors.o
++In file included from ../cpp/accessors.cpp:9:
++In file included from ../../nan.h:51:
++In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61:
++/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope'
++  return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
++                                        ~~~~~~~~~~~~~^~~~~~~~~~~~
++```
++
++This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make
++`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore
++this patch cannot be released by either project in an official release.
++
++For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support
++that configuration, you will need to either get an older compiler, or apply a source patch to the version
++of V8 headers as a workaround.
++
++<a name="governance"></a>
++
++## Governance & Contributing
++
++NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api)
++
++### Addon API Working Group (WG)
++
++The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
++
++Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects.
++
++The WG has final authority over this project including:
++
++* Technical direction
++* Project governance and process (including this policy)
++* Contribution policy
++* GitHub repository hosting
++* Maintaining the list of additional Collaborators
++
++For the current list of WG members, see the project [README.md](./README.md#collaborators).
++
++Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
++
++_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
++
++For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
++
++### Consensus Seeking Process
++
++The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
++
++Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
++
++If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
++
++<a id="developers-certificate-of-origin"></a>
++
++## Developer's Certificate of Origin 1.1
++
++By making a contribution to this project, I certify that:
++
++* (a) The contribution was created in whole or in part by me and I
++  have the right to submit it under the open source license
++  indicated in the file; or
++
++* (b) The contribution is based upon previous work that, to the best
++  of my knowledge, is covered under an appropriate open source
++  license and I have the right under that license to submit that
++  work with modifications, whether created in whole or in part
++  by me, under the same open source license (unless I am
++  permitted to submit under a different license), as indicated
++  in the file; or
++
++* (c) The contribution was provided directly to me by some other
++  person who certified (a), (b) or (c) and I have not modified
++  it.
++
++* (d) I understand and agree that this project and the contribution
++  are public and that a record of the contribution (including all
++  personal information I submit with it, including my sign-off) is
++  maintained indefinitely and may be redistributed consistent with
++  this project or the open source license(s) involved.
++
++<a name="collaborators"></a>
++
++### WG Members / Collaborators
++
++<table><tbody>
++<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
++<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
++<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
++<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
++<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
++<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
++<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr>
++<tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr>
++</tbody></table>
++
++## Licence &amp; copyright
++
++Copyright (c) 2018 NAN WG Members / Collaborators (listed above).
++
++Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..04231f83ce6e480d4a37902588692a00f3d958e6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,146 @@@
++## Asynchronous work helpers
++
++`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
++
++ - <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
++ - <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
++ - <a href="#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
++ - <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
++
++<a name="api_nan_async_worker"></a>
++### Nan::AsyncWorker
++
++`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress.
++
++This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the
++correct async context. To be able to identify the async resources created by this class in async-hooks, provide a
++`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid
++collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation.  The `resource_name` needs to stay valid for the lifetime of the worker instance.
++
++Definition:
++
++```c++
++class AsyncWorker {
++ public:
++  explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker");
++
++  virtual ~AsyncWorker();
++
++  virtual void WorkComplete();
++
++  void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value);
++
++  void SaveToPersistent(const v8::Local<v8::String> &key,
++                        const v8::Local<v8::Value> &value);
++
++  void SaveToPersistent(uint32_t index,
++                        const v8::Local<v8::Value> &value);
++
++  v8::Local<v8::Value> GetFromPersistent(const char *key) const;
++
++  v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const;
++
++  v8::Local<v8::Value> GetFromPersistent(uint32_t index) const;
++
++  virtual void Execute() = 0;
++
++  uv_work_t request;
++
++  virtual void Destroy();
++
++ protected:
++  Persistent<v8::Object> persistentHandle;
++
++  Callback *callback;
++
++  virtual void HandleOKCallback();
++
++  virtual void HandleErrorCallback();
++
++  void SetErrorMessage(const char *msg);
++
++  const char* ErrorMessage();
++};
++```
++
++<a name="api_nan_async_progress_worker"></a>
++### Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker
++
++`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
++
++Previously the definition of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `<char>` for compatibility.
++
++`Nan::AsyncProgressWorkerBase` &amp; `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar.  The last event sent before the main thread is woken will be delivered.
++
++Definition:
++
++```c++
++template<class T>
++class AsyncProgressWorkerBase<T> : public AsyncWorker {
++ public:
++  explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...);
++
++  virtual ~AsyncProgressWorkerBase();
++
++  void WorkProgress();
++
++  class ExecutionProgress {
++   public:
++    void Signal() const;
++    void Send(const T* data, size_t count) const;
++  };
++
++  virtual void Execute(const ExecutionProgress& progress) = 0;
++
++  virtual void HandleProgressCallback(const T *data, size_t count) = 0;
++
++  virtual void Destroy();
++};
++
++typedef AsyncProgressWorkerBase<T> AsyncProgressWorker;
++```
++
++<a name="api_nan_async_progress_queue_worker"></a>
++### Nan::AsyncProgressQueueWorker
++
++`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
++
++`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread.
++
++Definition:
++
++```c++
++template<class T>
++class AsyncProgressQueueWorker<T> : public AsyncWorker {
++ public:
++  explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker");
++
++  virtual ~AsyncProgressQueueWorker();
++
++  void WorkProgress();
++
++  class ExecutionProgress {
++   public:
++    void Send(const T* data, size_t count) const;
++  };
++
++  virtual void Execute(const ExecutionProgress& progress) = 0;
++
++  virtual void HandleProgressCallback(const T *data, size_t count) = 0;
++
++  virtual void Destroy();
++};
++```
++
++<a name="api_nan_async_queue_worker"></a>
++### Nan::AsyncQueueWorker
++
++`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`.
++
++Definition:
++
++```c++
++void AsyncQueueWorker(AsyncWorker *);
++```
++
++[AsyncResource]: node_misc.md#api_nan_asyncresource
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8d8d25cf75a854d989ef7bc498caa7721913b89a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,54 @@@
++## Buffers
++
++NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
++
++ - <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
++ - <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
++ - <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
++
++<a name="api_nan_new_buffer"></a>
++### Nan::NewBuffer()
++
++Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`.
++
++Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management.
++When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`.
++You _must not_ free the memory space manually once you have created a `Buffer` in this way.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size)
++Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size)
++Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data,
++                                           size_t length,
++                                           Nan::FreeCallback callback,
++                                           void *hint)
++```
++
++
++<a name="api_nan_copy_buffer"></a>
++### Nan::CopyBuffer()
++
++Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`.
++
++Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size)
++```
++
++
++<a name="api_nan_free_callback"></a>
++### Nan::FreeCallback()
++
++A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer).
++The supplied callback will be invoked when the `Buffer` undergoes garbage collection.
++
++Signature:
++
++```c++
++typedef void (*FreeCallback)(char *data, void *hint);
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..f7af0bfd9d8281f2eb7e16fc57e787ce54ebeda2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,76 @@@
++## Nan::Callback
++
++`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
++
++ - <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a>
++
++<a name="api_nan_callback"></a>
++### Nan::Callback
++
++```c++
++class Callback {
++ public:
++  Callback();
++
++  explicit Callback(const v8::Local<v8::Function> &fn);
++
++  ~Callback();
++
++  bool operator==(const Callback &other) const;
++
++  bool operator!=(const Callback &other) const;
++
++  v8::Local<v8::Function> operator*() const;
++
++  MaybeLocal<v8::Value> operator()(AsyncResource* async_resource,
++                                   v8::Local<v8::Object> target,
++                                   int argc = 0,
++                                   v8::Local<v8::Value> argv[] = 0) const;
++
++  MaybeLocal<v8::Value> operator()(AsyncResource* async_resource,
++                                   int argc = 0,
++                                   v8::Local<v8::Value> argv[] = 0) const;
++
++  void SetFunction(const v8::Local<v8::Function> &fn);
++
++  v8::Local<v8::Function> GetFunction() const;
++
++  bool IsEmpty() const;
++
++  void Reset(const v8::Local<v8::Function> &fn);
++
++  void Reset();
++
++  MaybeLocal<v8::Value> Call(v8::Local<v8::Object> target,
++                            int argc,
++                            v8::Local<v8::Value> argv[],
++                            AsyncResource* async_resource) const;
++  MaybeLocal<v8::Value> Call(int argc,
++                             v8::Local<v8::Value> argv[],
++                             AsyncResource* async_resource) const;
++
++  // Deprecated versions. Use the versions that accept an async_resource instead
++  // as they run the callback in the correct async context as specified by the
++  // resource. If you want to call a synchronous JS function (i.e. on a
++  // non-empty JS stack), you can use Nan::Call instead.
++  v8::Local<v8::Value> operator()(v8::Local<v8::Object> target,
++                                  int argc = 0,
++                                  v8::Local<v8::Value> argv[] = 0) const;
++
++  v8::Local<v8::Value> operator()(int argc = 0,
++                                  v8::Local<v8::Value> argv[] = 0) const;
++  v8::Local<v8::Value> Call(v8::Local<v8::Object> target,
++                            int argc,
++                            v8::Local<v8::Value> argv[]) const;
++
++  v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const;
++};
++```
++
++Example usage:
++
++```c++
++v8::Local<v8::Function> function;
++Nan::Callback callback(function);
++callback.Call(0, 0);
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d20861b5935b6208b594b91f67cabd27a2bb5558
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,41 @@@
++## Converters
++
++NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
++
++ - <a href="#api_nan_to"><b><code>Nan::To()</code></b></a>
++
++<a name="api_nan_to"></a>
++### Nan::To()
++
++Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly.
++
++See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types.
++
++Signatures:
++
++```c++
++// V8 types
++Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val);
++Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val);
++Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val);
++Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val);
++Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val);
++Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val);
++Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val);
++
++// Native types
++Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val);
++Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val);
++Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val);
++Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val);
++Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val);
++```
++
++### Example
++
++```c++
++v8::Local<v8::Value> val;
++Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val);
++Nan::Maybe<double> d = Nan::To<double>(val);
++```
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8127a548383b406e684f4c8bc8e56be423a3775c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,226 @@@
++## Errors
++
++NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
++
++Note that an Error object is simply a specialized form of `v8::Value`.
++
++Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
++
++ - <a href="#api_nan_error"><b><code>Nan::Error()</code></b></a>
++ - <a href="#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
++ - <a href="#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
++ - <a href="#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
++ - <a href="#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
++ - <a href="#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
++ - <a href="#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
++ - <a href="#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
++ - <a href="#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
++ - <a href="#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
++ - <a href="#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
++ - <a href="#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
++ - <a href="#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
++
++
++<a name="api_nan_error"></a>
++### Nan::Error()
++
++Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
++
++Note that an Error object is simply a specialized form of `v8::Value`.
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::Error(const char *msg);
++v8::Local<v8::Value> Nan::Error(v8::Local<v8::String> msg);
++```
++
++
++<a name="api_nan_range_error"></a>
++### Nan::RangeError()
++
++Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
++
++Note that an RangeError object is simply a specialized form of `v8::Value`.
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::RangeError(const char *msg);
++v8::Local<v8::Value> Nan::RangeError(v8::Local<v8::String> msg);
++```
++
++
++<a name="api_nan_reference_error"></a>
++### Nan::ReferenceError()
++
++Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
++
++Note that an ReferenceError object is simply a specialized form of `v8::Value`.
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::ReferenceError(const char *msg);
++v8::Local<v8::Value> Nan::ReferenceError(v8::Local<v8::String> msg);
++```
++
++
++<a name="api_nan_syntax_error"></a>
++### Nan::SyntaxError()
++
++Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
++
++Note that an SyntaxError object is simply a specialized form of `v8::Value`.
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::SyntaxError(const char *msg);
++v8::Local<v8::Value> Nan::SyntaxError(v8::Local<v8::String> msg);
++```
++
++
++<a name="api_nan_type_error"></a>
++### Nan::TypeError()
++
++Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
++
++Note that an TypeError object is simply a specialized form of `v8::Value`.
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::TypeError(const char *msg);
++v8::Local<v8::Value> Nan::TypeError(v8::Local<v8::String> msg);
++```
++
++
++<a name="api_nan_throw_error"></a>
++### Nan::ThrowError()
++
++Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created.
++
++Signature:
++
++```c++
++void Nan::ThrowError(const char *msg);
++void Nan::ThrowError(v8::Local<v8::String> msg);
++void Nan::ThrowError(v8::Local<v8::Value> error);
++```
++
++
++<a name="api_nan_throw_range_error"></a>
++### Nan::ThrowRangeError()
++
++Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created.
++
++Signature:
++
++```c++
++void Nan::ThrowRangeError(const char *msg);
++void Nan::ThrowRangeError(v8::Local<v8::String> msg);
++void Nan::ThrowRangeError(v8::Local<v8::Value> error);
++```
++
++
++<a name="api_nan_throw_reference_error"></a>
++### Nan::ThrowReferenceError()
++
++Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created.
++
++Signature:
++
++```c++
++void Nan::ThrowReferenceError(const char *msg);
++void Nan::ThrowReferenceError(v8::Local<v8::String> msg);
++void Nan::ThrowReferenceError(v8::Local<v8::Value> error);
++```
++
++
++<a name="api_nan_throw_syntax_error"></a>
++### Nan::ThrowSyntaxError()
++
++Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created.
++
++Signature:
++
++```c++
++void Nan::ThrowSyntaxError(const char *msg);
++void Nan::ThrowSyntaxError(v8::Local<v8::String> msg);
++void Nan::ThrowSyntaxError(v8::Local<v8::Value> error);
++```
++
++
++<a name="api_nan_throw_type_error"></a>
++### Nan::ThrowTypeError()
++
++Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created.
++
++Signature:
++
++```c++
++void Nan::ThrowTypeError(const char *msg);
++void Nan::ThrowTypeError(v8::Local<v8::String> msg);
++void Nan::ThrowTypeError(v8::Local<v8::Value> error);
++```
++
++<a name="api_nan_fatal_exception"></a>
++### Nan::FatalException()
++
++Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch).
++
++Signature:
++
++```c++
++void Nan::FatalException(const Nan::TryCatch& try_catch);
++```
++
++<a name="api_nan_errno_exception"></a>
++### Nan::ErrnoException()
++
++Replaces `node::ErrnoException()` which has a different API across supported versions of Node. 
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::ErrnoException(int errorno,
++                                         const char* syscall = NULL,
++                                         const char* message = NULL,
++                                         const char* path = NULL);
++```
++
++
++<a name="api_nan_try_catch"></a>
++### Nan::TryCatch
++
++A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/node-8.11/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`.
++
++Signature:
++
++```c++
++class Nan::TryCatch {
++ public:
++  Nan::TryCatch();
++
++  bool HasCaught() const;
++
++  bool CanContinue() const;
++
++  v8::Local<v8::Value> ReThrow();
++
++  v8::Local<v8::Value> Exception() const;
++
++  // Nan::MaybeLocal for older versions of V8
++  v8::MaybeLocal<v8::Value> StackTrace() const;
++
++  v8::Local<v8::Message> Message() const;
++
++  void Reset();
++
++  void SetVerbose(bool value);
++
++  void SetCaptureMessage(bool value);
++};
++```
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4fa78dbabc0986d8730e0ac93c9a43b40c7bca1d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,62 @@@
++## JSON
++
++The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
++
++ - <a href="#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
++ - <a href="#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
++
++Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
++
++<a name="api_nan_json_parse"></a>
++
++### Nan::JSON.Parse
++
++A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504).
++
++Definition:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::JSON::Parse(v8::Local<v8::String> json_string);
++```
++
++Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`.
++
++Example:
++
++```c++
++v8::Local<v8::String> json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked();
++
++Nan::JSON NanJSON;
++Nan::MaybeLocal<v8::Value> result = NanJSON.Parse(json_string);
++if (!result.IsEmpty()) {
++  v8::Local<v8::Value> val = result.ToLocalChecked();
++}
++```
++
++<a name="api_nan_json_stringify"></a>
++
++### Nan::JSON.Stringify
++
++A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860).
++
++Definition:
++
++```c++
++Nan::MaybeLocal<v8::String> Nan::JSON::Stringify(v8::Local<v8::Object> json_object, v8::Local<v8::String> gap = v8::Local<v8::String>());
++```
++
++Use `JSON.Stringify(value)` to stringify a `v8::Object`.
++
++Example:
++
++```c++
++// using `v8::Local<v8::Value> val` from the `JSON::Parse` example
++v8::Local<v8::Object> obj = Nan::To<v8::Object>(val).ToLocalChecked();
++
++Nan::JSON NanJSON;
++Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj);
++if (!result.IsEmpty()) {
++  v8::Local<v8::String> stringified = result.ToLocalChecked();
++}
++```
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1a9fabf7b141f77620b576780aa39e8ccfd3769b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,583 @@@
++## Maybe Types
++
++The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
++
++* **Maybe Types**
++  - <a href="#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
++  - <a href="#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
++  - <a href="#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
++  - <a href="#api_nan_just"><b><code>Nan::Just</code></b></a>
++* **Maybe Helpers**
++  - <a href="#api_nan_call"><b><code>Nan::Call()</code></b></a>
++  - <a href="#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
++  - <a href="#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
++  - <a href="#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
++  - <a href="#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
++  - <a href="#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
++  - <a href="#api_nan_set"><b><code>Nan::Set()</code></b></a>
++  - <a href="#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
++  - <a href="#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
++  - <a href="#api_nan_get"><b><code>Nan::Get()</code></b></a>
++  - <a href="#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
++  - <a href="#api_nan_has"><b><code>Nan::Has()</code></b></a>
++  - <a href="#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
++  - <a href="#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
++  - <a href="#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
++  - <a href="#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
++  - <a href="#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
++  - <a href="#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
++  - <a href="#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
++  - <a href="#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
++  - <a href="#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
++  - <a href="#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
++  - <a href="#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
++  - <a href="#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
++  - <a href="#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
++  - <a href="#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
++  - <a href="#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
++  - <a href="#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
++  - <a href="#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
++  - <a href="#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
++  - <a href="#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
++  - <a href="#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
++  - <a href="#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
++  - <a href="#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
++  - <a href="#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
++
++<a name="api_nan_maybe_local"></a>
++### Nan::MaybeLocal
++
++A `Nan::MaybeLocal<T>` is a wrapper around [`v8::Local<T>`](https://v8docs.nodesource.com/node-8.11/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local<T>` is empty before it can be used.
++
++If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned.
++
++Definition:
++
++```c++
++template<typename T> class Nan::MaybeLocal {
++ public:
++  MaybeLocal();
++
++  template<typename S> MaybeLocal(v8::Local<S> that);
++
++  bool IsEmpty() const;
++
++  template<typename S> bool ToLocal(v8::Local<S> *out);
++
++  // Will crash if the MaybeLocal<> is empty.
++  v8::Local<T> ToLocalChecked();
++
++  template<typename S> v8::Local<S> FromMaybe(v8::Local<S> default_value) const;
++};
++```
++
++See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/node-8.11/d8/d7d/classv8_1_1_maybe_local.html) for further details.
++
++<a name="api_nan_maybe"></a>
++### Nan::Maybe
++
++A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
++
++If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned.
++
++Definition:
++
++```c++
++template<typename T> class Nan::Maybe {
++ public:
++  bool IsNothing() const;
++  bool IsJust() const;
++
++  // Will crash if the Maybe<> is nothing.
++  T FromJust();
++
++  T FromMaybe(const T& default_value);
++
++  bool operator==(const Maybe &other);
++
++  bool operator!=(const Maybe &other);
++};
++```
++
++See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/node-8.11/d9/d4b/classv8_1_1_maybe.html) for further details.
++
++<a name="api_nan_nothing"></a>
++### Nan::Nothing
++
++Construct an empty `Nan::Maybe` type representing _nothing_.
++
++```c++
++template<typename T> Nan::Maybe<T> Nan::Nothing();
++```
++
++<a name="api_nan_just"></a>
++### Nan::Just
++
++Construct a `Nan::Maybe` type representing _just_ a value.
++
++```c++
++template<typename T> Nan::Maybe<T> Nan::Just(const T &t);
++```
++
++<a name="api_nan_call"></a>
++### Nan::Call()
++
++A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/node-8.11/d5/d54/classv8_1_1_function.html#a9c3d0e4e13ddd7721fce238aa5b94a11) in a way compatible across supported versions of V8.
++
++For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::Call(v8::Local<v8::Function> fun, v8::Local<v8::Object> recv, int argc, v8::Local<v8::Value> argv[]);
++Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, v8::Local<v8::Object> recv,
++ int argc, v8::Local<v8::Value> argv[]);
++Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, int argc, v8::Local<v8::Value> argv[]);
++```
++
++
++<a name="api_nan_to_detail_string"></a>
++### Nan::ToDetailString()
++
++A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/node-8.11/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::String> Nan::ToDetailString(v8::Local<v8::Value> val);
++```
++
++
++<a name="api_nan_to_array_index"></a>
++### Nan::ToArrayIndex()
++
++A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/node-8.11/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Uint32> Nan::ToArrayIndex(v8::Local<v8::Value> val);
++```
++
++
++<a name="api_nan_equals"></a>
++### Nan::Equals()
++
++A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/node-8.11/dc/d0a/classv8_1_1_value.html#a08fba1d776a59bbf6864b25f9152c64b) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b));
++```
++
++
++<a name="api_nan_new_instance"></a>
++### Nan::NewInstance()
++
++A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/node-8.11/d5/d54/classv8_1_1_function.html#ae477558b10c14b76ed00e8dbab44ce5b) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h);
++Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h, int argc, v8::Local<v8::Value> argv[]);
++Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::ObjectTemplate> h);
++```
++
++
++<a name="api_nan_get_function"></a>
++### Nan::GetFunction()
++
++A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/node-8.11/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Function> Nan::GetFunction(v8::Local<v8::FunctionTemplate> t);
++```
++
++
++<a name="api_nan_set"></a>
++### Nan::Set()
++
++A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
++                          v8::Local<v8::Value> key,
++                          v8::Local<v8::Value> value)
++Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
++                          uint32_t index,
++                          v8::Local<v8::Value> value);
++```
++
++
++<a name="api_nan_define_own_property"></a>
++### Nan::DefineOwnProperty()
++
++A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::DefineOwnProperty(v8::Local<v8::Object> obj,
++                                        v8::Local<v8::String> key,
++                                        v8::Local<v8::Value> value,
++                                        v8::PropertyAttribute attribs = v8::None);
++```
++
++
++<a name="api_nan_force_set"></a>
++### <del>Nan::ForceSet()</del>
++
++Deprecated, use <a href="#api_nan_define_own_property"><code>Nan::DefineOwnProperty()</code></a>.
++
++<del>A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/node-0.12/db/d85/classv8_1_1_object.html#acfbdfd7427b516ebdb5c47c4df5ed96c) in a way compatible across supported versions of V8.</del>
++
++Signature:
++
++```c++
++NAN_DEPRECATED Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object> obj,
++                                              v8::Local<v8::Value> key,
++                                              v8::Local<v8::Value> value,
++                                              v8::PropertyAttribute attribs = v8::None);
++```
++
++
++<a name="api_nan_get"></a>
++### Nan::Get()
++
++A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj,
++                                    v8::Local<v8::Value> key);
++Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, uint32_t index);
++```
++
++
++<a name="api_nan_get_property_attribute"></a>
++### Nan::GetPropertyAttributes()
++
++A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<v8::PropertyAttribute> Nan::GetPropertyAttributes(
++    v8::Local<v8::Object> obj,
++    v8::Local<v8::Value> key);
++```
++
++
++<a name="api_nan_has"></a>
++### Nan::Has()
++
++A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, v8::Local<v8::String> key);
++Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, uint32_t index);
++```
++
++
++<a name="api_nan_delete"></a>
++### Nan::Delete()
++
++A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a48e4a19b2cedff867eecc73ddb7d377f) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj,
++                             v8::Local<v8::String> key);
++Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, uint32_t index);
++```
++
++
++<a name="api_nan_get_property_names"></a>
++### Nan::GetPropertyNames()
++
++A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Array> Nan::GetPropertyNames(v8::Local<v8::Object> obj);
++```
++
++
++<a name="api_nan_get_own_property_names"></a>
++### Nan::GetOwnPropertyNames()
++
++A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Array> Nan::GetOwnPropertyNames(v8::Local<v8::Object> obj);
++```
++
++
++<a name="api_nan_set_prototype"></a>
++### Nan::SetPrototype()
++
++A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::SetPrototype(v8::Local<v8::Object> obj,
++                                   v8::Local<v8::Value> prototype);
++```
++
++
++<a name="api_nan_object_proto_to_string"></a>
++### Nan::ObjectProtoToString()
++
++A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::String> Nan::ObjectProtoToString(v8::Local<v8::Object> obj);
++```
++
++
++<a name="api_nan_has_own_property"></a>
++### Nan::HasOwnProperty()
++
++A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::HasOwnProperty(v8::Local<v8::Object> obj,
++                                     v8::Local<v8::String> key);
++```
++
++
++<a name="api_nan_has_real_named_property"></a>
++### Nan::HasRealNamedProperty()
++
++A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::HasRealNamedProperty(v8::Local<v8::Object> obj,
++                                           v8::Local<v8::String> key);
++```
++
++
++<a name="api_nan_has_real_indexed_property"></a>
++### Nan::HasRealIndexedProperty()
++
++A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::HasRealIndexedProperty(v8::Local<v8::Object> obj,
++                                             uint32_t index);
++```
++
++
++<a name="api_nan_has_real_named_callback_property"></a>
++### Nan::HasRealNamedCallbackProperty()
++
++A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::HasRealNamedCallbackProperty(
++    v8::Local<v8::Object> obj,
++    v8::Local<v8::String> key);
++```
++
++
++<a name="api_nan_get_real_named_property_in_prototype_chain"></a>
++### Nan::GetRealNamedPropertyInPrototypeChain()
++
++A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::GetRealNamedPropertyInPrototypeChain(
++    v8::Local<v8::Object> obj,
++    v8::Local<v8::String> key);
++```
++
++
++<a name="api_nan_get_real_named_property"></a>
++### Nan::GetRealNamedProperty()
++
++A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::GetRealNamedProperty(v8::Local<v8::Object> obj,
++                                                     v8::Local<v8::String> key);
++```
++
++
++<a name="api_nan_call_as_function"></a>
++### Nan::CallAsFunction()
++
++A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ad3ffc36f3dfc3592ce2a96bc047ee2cd) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::CallAsFunction(v8::Local<v8::Object> obj,
++                                               v8::Local<v8::Object> recv,
++                                               int argc,
++                                               v8::Local<v8::Value> argv[]);
++```
++
++
++<a name="api_nan_call_as_constructor"></a>
++### Nan::CallAsConstructor()
++
++A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::CallAsConstructor(v8::Local<v8::Object> obj,
++                                                  int argc,
++                                                  v8::Local<v8::Value> argv[]);
++```
++
++
++<a name="api_nan_get_source_line"></a>
++### Nan::GetSourceLine()
++
++A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::String> Nan::GetSourceLine(v8::Local<v8::Message> msg);
++```
++
++
++<a name="api_nan_get_line_number"></a>
++### Nan::GetLineNumber()
++
++A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<int> Nan::GetLineNumber(v8::Local<v8::Message> msg);
++```
++
++
++<a name="api_nan_get_start_column"></a>
++### Nan::GetStartColumn()
++
++A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<int> Nan::GetStartColumn(v8::Local<v8::Message> msg);
++```
++
++
++<a name="api_nan_get_end_column"></a>
++### Nan::GetEndColumn()
++
++A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<int> Nan::GetEndColumn(v8::Local<v8::Message> msg);
++```
++
++
++<a name="api_nan_clone_element_at"></a>
++### Nan::CloneElementAt()
++
++A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/node-4.8/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array> array, uint32_t index);
++```
++
++<a name="api_nan_has_private"></a>
++### Nan::HasPrivate()
++
++A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
++```
++
++<a name="api_nan_get_private"></a>
++### Nan::GetPrivate()
++
++A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
++```
++
++<a name="api_nan_set_private"></a>
++### Nan::SetPrivate()
++
++A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value);
++```
++
++<a name="api_nan_delete_private"></a>
++### Nan::DeletePrivate()
++
++A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8.
++
++Signature:
++
++```c++
++Nan::Maybe<bool> Nan::DeletePrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
++```
++
++<a name="api_nan_make_maybe"></a>
++### Nan::MakeMaybe()
++
++Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN.
++
++Synopsis:
++
++```c++
++  MaybeLocal<v8::Number> someNumber = MakeMaybe(New<v8::Number>(3.141592654));
++  MaybeLocal<v8::String> someString = MakeMaybe(New<v8::String>("probably"));
++```
++
++Signature:
++
++```c++
++template <typename T, template <typename> class MaybeMaybe>
++Nan::MaybeLocal<T> Nan::MakeMaybe(MaybeMaybe<T> v);
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b2b26c38a63a9c3d9ec001fc8a356076584f4add
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,661 @@@
++## JavaScript-accessible methods
++
++A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
++
++In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
++
++* **Method argument types**
++ - <a href="#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
++ - <a href="#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
++ - <a href="#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
++* **Method declarations**
++ - <a href="#api_nan_method"><b>Method declaration</b></a>
++ - <a href="#api_nan_getter"><b>Getter declaration</b></a>
++ - <a href="#api_nan_setter"><b>Setter declaration</b></a>
++ - <a href="#api_nan_property_getter"><b>Property getter declaration</b></a>
++ - <a href="#api_nan_property_setter"><b>Property setter declaration</b></a>
++ - <a href="#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
++ - <a href="#api_nan_property_deleter"><b>Property deleter declaration</b></a>
++ - <a href="#api_nan_property_query"><b>Property query declaration</b></a>
++ - <a href="#api_nan_index_getter"><b>Index getter declaration</b></a>
++ - <a href="#api_nan_index_setter"><b>Index setter declaration</b></a>
++ - <a href="#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
++ - <a href="#api_nan_index_deleter"><b>Index deleter declaration</b></a>
++ - <a href="#api_nan_index_query"><b>Index query declaration</b></a>
++* Method and template helpers
++ - <a href="#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
++ - <a href="#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
++ - <a href="#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
++ - <a href="#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
++ - <a href="#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
++ - <a href="#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
++ - <a href="#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
++ - <a href="#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
++ - <a href="#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
++ - <a href="#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
++
++<a name="api_nan_function_callback_info"></a>
++### Nan::FunctionCallbackInfo
++
++`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.11/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist.
++
++Definition:
++
++```c++
++template<typename T> class FunctionCallbackInfo {
++ public:
++  ReturnValue<T> GetReturnValue() const;
++  v8::Local<v8::Function> Callee(); // NOTE: Not available in NodeJS >= 10.0.0
++  v8::Local<v8::Value> Data();
++  v8::Local<v8::Object> Holder();
++  bool IsConstructCall();
++  int Length() const;
++  v8::Local<v8::Value> operator[](int i) const;
++  v8::Local<v8::Object> This() const;
++  v8::Isolate *GetIsolate() const;
++};
++```
++
++See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.11/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods.
++
++**Note:** `FunctionCallbackInfo::Callee` is removed in Node.js after `10.0.0` because it is was deprecated in V8. Consider using `info.Data()` to pass any information you need.
++
++<a name="api_nan_property_callback_info"></a>
++### Nan::PropertyCallbackInfo
++
++`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.11/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist.
++
++Definition:
++
++```c++
++template<typename T> class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
++ public:
++  ReturnValue<T> GetReturnValue() const;
++  v8::Isolate* GetIsolate() const;
++  v8::Local<v8::Value> Data() const;
++  v8::Local<v8::Object> This() const;
++  v8::Local<v8::Object> Holder() const;
++};
++```
++
++See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.11/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods.
++
++<a name="api_nan_return_value"></a>
++### Nan::ReturnValue
++
++`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.11/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`.
++
++Example usage:
++
++```c++
++void EmptyArray(const Nan::FunctionCallbackInfo<v8::Value>& info) {
++  info.GetReturnValue().Set(Nan::New<v8::Array>());
++}
++```
++
++Definition:
++
++```c++
++template<typename T> class ReturnValue {
++ public:
++  // Handle setters
++  template <typename S> void Set(const v8::Local<S> &handle);
++  template <typename S> void Set(const Nan::Global<S> &handle);
++
++  // Fast primitive setters
++  void Set(bool value);
++  void Set(double i);
++  void Set(int32_t i);
++  void Set(uint32_t i);
++
++  // Fast JS primitive setters
++  void SetNull();
++  void SetUndefined();
++  void SetEmptyString();
++
++  // Convenience getter for isolate
++  v8::Isolate *GetIsolate() const;
++};
++```
++
++See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.11/da/da7/classv8_1_1_return_value.html) for further information on this.
++
++<a name="api_nan_method"></a>
++### Method declaration
++
++JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`:
++
++```c++
++typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
++```
++
++Example:
++
++```c++
++void MethodName(const Nan::FunctionCallbackInfo<v8::Value>& info) {
++  ...
++}
++```
++
++You do not need to declare a new `HandleScope` within a method as one is implicitly created for you.
++
++**Example usage**
++
++```c++
++// .h:
++class Foo : public Nan::ObjectWrap {
++  ...
++
++  static void Bar(const Nan::FunctionCallbackInfo<v8::Value>& info);
++  static void Baz(const Nan::FunctionCallbackInfo<v8::Value>& info);
++}
++
++
++// .cc:
++void Foo::Bar(const Nan::FunctionCallbackInfo<v8::Value>& info) {
++  ...
++}
++
++void Foo::Baz(const Nan::FunctionCallbackInfo<v8::Value>& info) {
++  ...
++}
++```
++
++A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations.
++
++**Example usage with `NAN_METHOD(methodname)`**
++
++```c++
++// .h:
++class Foo : public Nan::ObjectWrap {
++  ...
++
++  static NAN_METHOD(Bar);
++  static NAN_METHOD(Baz);
++}
++
++
++// .cc:
++NAN_METHOD(Foo::Bar) {
++  ...
++}
++
++NAN_METHOD(Foo::Baz) {
++  ...
++}
++```
++
++Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object.
++
++<a name="api_nan_getter"></a>
++### Getter declaration
++
++JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`:
++
++```c++
++typedef void(*GetterCallback)(v8::Local<v8::String>,
++                              const PropertyCallbackInfo<v8::Value>&);
++```
++
++Example:
++
++```c++
++void GetterName(v8::Local<v8::String> property,
++                const Nan::PropertyCallbackInfo<v8::Value>& info) {
++  ...
++}
++```
++
++You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you.
++
++A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
++
++<a name="api_nan_setter"></a>
++### Setter declaration
++
++JavaScript-accessible setters should be declared with the following signature to form a <b><code>Nan::SetterCallback</code></b>:
++
++```c++
++typedef void(*SetterCallback)(v8::Local<v8::String>,
++                              v8::Local<v8::Value>,
++                              const PropertyCallbackInfo<void>&);
++```
++
++Example:
++
++```c++
++void SetterName(v8::Local<v8::String> property,
++                v8::Local<v8::Value> value,
++                const Nan::PropertyCallbackInfo<void>& info) {
++  ...
++}
++```
++
++You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you.
++
++A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
++
++<a name="api_nan_property_getter"></a>
++### Property getter declaration
++
++JavaScript-accessible property getters should be declared with the following signature to form a <b><code>Nan::PropertyGetterCallback</code></b>:
++
++```c++
++typedef void(*PropertyGetterCallback)(v8::Local<v8::String>,
++                                      const PropertyCallbackInfo<v8::Value>&);
++```
++
++Example:
++
++```c++
++void PropertyGetterName(v8::Local<v8::String> property,
++                        const Nan::PropertyCallbackInfo<v8::Value>& info) {
++  ...
++}
++```
++
++You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you.
++
++A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_property_setter"></a>
++### Property setter declaration
++
++JavaScript-accessible property setters should be declared with the following signature to form a <b><code>Nan::PropertySetterCallback</code></b>:
++
++```c++
++typedef void(*PropertySetterCallback)(v8::Local<v8::String>,
++                                      v8::Local<v8::Value>,
++                                      const PropertyCallbackInfo<v8::Value>&);
++```
++
++Example:
++
++```c++
++void PropertySetterName(v8::Local<v8::String> property,
++                        v8::Local<v8::Value> value,
++                        const Nan::PropertyCallbackInfo<v8::Value>& info);
++```
++
++You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you.
++
++A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_property_enumerator"></a>
++### Property enumerator declaration
++
++JavaScript-accessible property enumerators should be declared with the following signature to form a <b><code>Nan::PropertyEnumeratorCallback</code></b>:
++
++```c++
++typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
++```
++
++Example:
++
++```c++
++void PropertyEnumeratorName(const Nan::PropertyCallbackInfo<v8::Array>& info);
++```
++
++You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you.
++
++A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_property_deleter"></a>
++### Property deleter declaration
++
++JavaScript-accessible property deleters should be declared with the following signature to form a <b><code>Nan::PropertyDeleterCallback</code></b>:
++
++```c++
++typedef void(*PropertyDeleterCallback)(v8::Local<v8::String>,
++                                       const PropertyCallbackInfo<v8::Boolean>&);
++```
++
++Example:
++
++```c++
++void PropertyDeleterName(v8::Local<v8::String> property,
++                         const Nan::PropertyCallbackInfo<v8::Boolean>& info);
++```
++
++You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you.
++
++A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_property_query"></a>
++### Property query declaration
++
++JavaScript-accessible property query methods should be declared with the following signature to form a <b><code>Nan::PropertyQueryCallback</code></b>:
++
++```c++
++typedef void(*PropertyQueryCallback)(v8::Local<v8::String>,
++                                     const PropertyCallbackInfo<v8::Integer>&);
++```
++
++Example:
++
++```c++
++void PropertyQueryName(v8::Local<v8::String> property,
++                       const Nan::PropertyCallbackInfo<v8::Integer>& info);
++```
++
++You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you.
++
++A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_index_getter"></a>
++### Index getter declaration
++
++JavaScript-accessible index getter methods should be declared with the following signature to form a <b><code>Nan::IndexGetterCallback</code></b>:
++
++```c++
++typedef void(*IndexGetterCallback)(uint32_t,
++                                   const PropertyCallbackInfo<v8::Value>&);
++```
++
++Example:
++
++```c++
++void IndexGetterName(uint32_t index, const PropertyCallbackInfo<v8::Value>& info);
++```
++
++You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you.
++
++A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_index_setter"></a>
++### Index setter declaration
++
++JavaScript-accessible index setter methods should be declared with the following signature to form a <b><code>Nan::IndexSetterCallback</code></b>:
++
++```c++
++typedef void(*IndexSetterCallback)(uint32_t,
++                                   v8::Local<v8::Value>,
++                                   const PropertyCallbackInfo<v8::Value>&);
++```
++
++Example:
++
++```c++
++void IndexSetterName(uint32_t index,
++                     v8::Local<v8::Value> value,
++                     const PropertyCallbackInfo<v8::Value>& info);
++```
++
++You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you.
++
++A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_index_enumerator"></a>
++### Index enumerator declaration
++
++JavaScript-accessible index enumerator methods should be declared with the following signature to form a <b><code>Nan::IndexEnumeratorCallback</code></b>:
++
++```c++
++typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
++```
++
++Example:
++
++```c++
++void IndexEnumeratorName(const PropertyCallbackInfo<v8::Array>& info);
++```
++
++You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you.
++
++A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_index_deleter"></a>
++### Index deleter declaration
++
++JavaScript-accessible index deleter methods should be declared with the following signature to form a <b><code>Nan::IndexDeleterCallback</code></b>:
++
++```c++
++typedef void(*IndexDeleterCallback)(uint32_t,
++                                    const PropertyCallbackInfo<v8::Boolean>&);
++```
++
++Example:
++
++```c++
++void IndexDeleterName(uint32_t index, const PropertyCallbackInfo<v8::Boolean>& info);
++```
++
++You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you.
++
++A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_index_query"></a>
++### Index query declaration
++
++JavaScript-accessible index query methods should be declared with the following signature to form a <b><code>Nan::IndexQueryCallback</code></b>:
++
++```c++
++typedef void(*IndexQueryCallback)(uint32_t,
++                                  const PropertyCallbackInfo<v8::Integer>&);
++```
++
++Example:
++
++```c++
++void IndexQueryName(uint32_t index, const PropertyCallbackInfo<v8::Integer>& info);
++```
++
++You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you.
++
++A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
++
++Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
++
++<a name="api_nan_set_method"></a>
++### Nan::SetMethod()
++
++Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
++
++Signature:
++
++```c++
++void Nan::SetMethod(v8::Local<v8::Object> recv,
++                    const char *name,
++                    Nan::FunctionCallback callback)
++void Nan::SetMethod(v8::Local<v8::Template> templ,
++                    const char *name,
++                    Nan::FunctionCallback callback)
++```
++
++<a name="api_nan_set_prototype_method"></a>
++### Nan::SetPrototypeMethod()
++
++Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
++
++Signature:
++
++```c++
++void Nan::SetPrototypeMethod(v8::Local<v8::FunctionTemplate> recv,
++                             const char* name,
++                             Nan::FunctionCallback callback)
++```
++
++<a name="api_nan_set_accessor"></a>
++### Nan::SetAccessor()
++
++Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see <a href="#api_nan_getter">Getter declaration</a>) and setters with the `Nan::SetterCallback` signature (see <a href="#api_nan_setter">Setter declaration</a>).
++
++Signature:
++
++```c++
++void SetAccessor(v8::Local<v8::ObjectTemplate> tpl,
++                 v8::Local<v8::String> name,
++                 Nan::GetterCallback getter,
++                 Nan::SetterCallback setter = 0,
++                 v8::Local<v8::Value> data = v8::Local<v8::Value>(),
++                 v8::AccessControl settings = v8::DEFAULT,
++                 v8::PropertyAttribute attribute = v8::None,
++                 imp::Sig signature = imp::Sig());
++bool SetAccessor(v8::Local<v8::Object> obj,
++                 v8::Local<v8::String> name,
++                 Nan::GetterCallback getter,
++                 Nan::SetterCallback setter = 0,
++                 v8::Local<v8::Value> data = v8::Local<v8::Value>(),
++                 v8::AccessControl settings = v8::DEFAULT,
++                 v8::PropertyAttribute attribute = v8::None)
++```
++
++See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ae91b3b56b357f285288c89fbddc46d1b) for further information about how to use `Nan::SetAccessor()`.
++
++<a name="api_nan_set_named_property_handler"></a>
++### Nan::SetNamedPropertyHandler()
++
++Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
++
++* Property getters with the `Nan::PropertyGetterCallback` signature (see <a href="#api_nan_property_getter">Property getter declaration</a>)
++* Property setters with the `Nan::PropertySetterCallback` signature (see <a href="#api_nan_property_setter">Property setter declaration</a>)
++* Property query methods with the `Nan::PropertyQueryCallback` signature (see <a href="#api_nan_property_query">Property query declaration</a>)
++* Property deleters with the `Nan::PropertyDeleterCallback` signature (see <a href="#api_nan_property_deleter">Property deleter declaration</a>)
++* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see <a href="#api_nan_property_enumerator">Property enumerator declaration</a>)
++
++Signature:
++
++```c++
++void SetNamedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
++                             Nan::PropertyGetterCallback getter,
++                             Nan::PropertySetterCallback setter = 0,
++                             Nan::PropertyQueryCallback query = 0,
++                             Nan::PropertyDeleterCallback deleter = 0,
++                             Nan::PropertyEnumeratorCallback enumerator = 0,
++                             v8::Local<v8::Value> data = v8::Local<v8::Value>())
++```
++
++See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#a33b3ebd7de641f6cc6414b7de01fc1c7) for further information about how to use `Nan::SetNamedPropertyHandler()`.
++
++<a name="api_nan_set_indexed_property_handler"></a>
++### Nan::SetIndexedPropertyHandler()
++
++Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
++
++* Indexed property getters with the `Nan::IndexGetterCallback` signature (see <a href="#api_nan_index_getter">Index getter declaration</a>)
++* Indexed property setters with the `Nan::IndexSetterCallback` signature (see <a href="#api_nan_index_setter">Index setter declaration</a>)
++* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see <a href="#api_nan_index_query">Index query declaration</a>)
++* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see <a href="#api_nan_index_deleter">Index deleter declaration</a>)
++* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see <a href="#api_nan_index_enumerator">Index enumerator declaration</a>)
++
++Signature:
++
++```c++
++void SetIndexedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
++                               Nan::IndexGetterCallback getter,
++                               Nan::IndexSetterCallback setter = 0,
++                               Nan::IndexQueryCallback query = 0,
++                               Nan::IndexDeleterCallback deleter = 0,
++                               Nan::IndexEnumeratorCallback enumerator = 0,
++                               v8::Local<v8::Value> data = v8::Local<v8::Value>())
++```
++
++See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`.
++
++<a name="api_nan_set_template"></a>
++### Nan::SetTemplate()
++
++Adds properties on an `Object`'s or `Function`'s template.
++
++Signature:
++
++```c++
++void Nan::SetTemplate(v8::Local<v8::Template> templ,
++                      const char *name,
++                      v8::Local<v8::Data> value);
++void Nan::SetTemplate(v8::Local<v8::Template> templ,
++                      v8::Local<v8::String> name,
++                      v8::Local<v8::Data> value,
++                      v8::PropertyAttribute attributes)
++```
++
++Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.11/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac).
++
++<a name="api_nan_set_prototype_template"></a>
++### Nan::SetPrototypeTemplate()
++
++Adds properties on an `Object`'s or `Function`'s prototype template.
++
++Signature:
++
++```c++
++void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
++                               const char *name,
++                               v8::Local<v8::Data> value);
++void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
++                               v8::Local<v8::String> name,
++                               v8::Local<v8::Data> value,
++                               v8::PropertyAttribute attributes)
++```
++
++Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.11/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
++
++<a name="api_nan_set_instance_template"></a>
++### Nan::SetInstanceTemplate()
++
++Use to add instance properties on `FunctionTemplate`'s.
++
++Signature:
++
++```c++
++void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
++                              const char *name,
++                              v8::Local<v8::Data> value);
++void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
++                              v8::Local<v8::String> name,
++                              v8::Local<v8::Data> value,
++                              v8::PropertyAttribute attributes)
++```
++
++Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.11/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
++
++<a name="api_nan_set_call_handler"></a>
++### Nan::SetCallHandler()
++
++Set the call-handler callback for a `v8::FunctionTemplate`.
++This callback is called whenever the function created from this FunctionTemplate is called.
++
++Signature:
++
++```c++
++void Nan::SetCallHandler(v8::Local<v8::FunctionTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>())
++```
++
++Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.11/d8/d83/classv8_1_1_function_template.html#ab7574b298db3c27fbc2ed465c08ea2f8).
++
++<a name="api_nan_set_call_as_function_handler"></a>
++### Nan::SetCallAsFunctionHandler()
++
++Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function.
++If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function.
++
++Signature:
++
++```c++
++void Nan::SetCallAsFunctionHandler(v8::Local<v8::ObjectTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>())
++```
++
++Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e).
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..359df4358de35a99eaab0a3a42f48e939fa134db
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,147 @@@
++## New
++
++NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
++
++ - <a href="#api_nan_new"><b><code>Nan::New()</code></b></a>
++ - <a href="#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
++ - <a href="#api_nan_null"><b><code>Nan::Null()</code></b></a>
++ - <a href="#api_nan_true"><b><code>Nan::True()</code></b></a>
++ - <a href="#api_nan_false"><b><code>Nan::False()</code></b></a>
++ - <a href="#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
++
++
++<a name="api_nan_new"></a>
++### Nan::New()
++
++`Nan::New()` should be used to instantiate new JavaScript objects.
++
++Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation.
++
++Signatures:
++
++Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local<T>`. The following types will be contained within a `Nan::MaybeLocal<T>`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`.
++
++Empty objects:
++
++```c++
++Nan::New<T>();
++```
++
++Generic single and multiple-argument:
++
++```c++
++Nan::New<T>(A0 arg0);
++Nan::New<T>(A0 arg0, A1 arg1);
++Nan::New<T>(A0 arg0, A1 arg1, A2 arg2);
++Nan::New<T>(A0 arg0, A1 arg1, A2 arg2, A3 arg3);
++```
++
++For creating `v8::FunctionTemplate` and `v8::Function` objects:
++
++_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._
++
++```c++
++Nan::New<T>(Nan::FunctionCallback callback,
++            v8::Local<v8::Value> data = v8::Local<v8::Value>());
++Nan::New<T>(Nan::FunctionCallback callback,
++            v8::Local<v8::Value> data = v8::Local<v8::Value>(),
++            A2 a2 = A2());
++```
++
++Native number types:
++
++```c++
++v8::Local<v8::Boolean> Nan::New<T>(bool value);
++v8::Local<v8::Int32> Nan::New<T>(int32_t value);
++v8::Local<v8::Uint32> Nan::New<T>(uint32_t value);
++v8::Local<v8::Number> Nan::New<T>(double value);
++```
++
++String types:
++
++```c++
++Nan::MaybeLocal<v8::String> Nan::New<T>(std::string const& value);
++Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value, int length);
++Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value);
++Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value);
++Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value, int length);
++```
++
++Specialized types:
++
++```c++
++v8::Local<v8::String> Nan::New<T>(v8::String::ExternalStringResource * value);
++v8::Local<v8::String> Nan::New<T>(Nan::ExternalOneByteStringResource * value);
++v8::Local<v8::RegExp> Nan::New<T>(v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
++```
++
++Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/node-8.11/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8.
++
++
++<a name="api_nan_undefined"></a>
++### Nan::Undefined()
++
++A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8.
++
++Signature:
++
++```c++
++v8::Local<v8::Primitive> Nan::Undefined()
++```
++
++<a name="api_nan_null"></a>
++### Nan::Null()
++
++A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8.
++
++Signature:
++
++```c++
++v8::Local<v8::Primitive> Nan::Null()
++```
++
++<a name="api_nan_true"></a>
++### Nan::True()
++
++A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8.
++
++Signature:
++
++```c++
++v8::Local<v8::Boolean> Nan::True()
++```
++
++<a name="api_nan_false"></a>
++### Nan::False()
++
++A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8.
++
++Signature:
++
++```c++
++v8::Local<v8::Boolean> Nan::False()
++```
++
++<a name="api_nan_empty_string"></a>
++### Nan::EmptyString()
++
++Call [`v8::String::Empty`](https://v8docs.nodesource.com/node-8.11/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8.
++
++Signature:
++
++```c++
++v8::Local<v8::String> Nan::EmptyString()
++```
++
++
++<a name="api_nan_new_one_byte_string"></a>
++### Nan::NewOneByteString()
++
++An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/node-8.11/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::String> Nan::NewOneByteString(const uint8_t * value,
++                                                  int length = -1)
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..17578e34907ff185fd0d8940afa2a78dae1fbda2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,123 @@@
++## Miscellaneous Node Helpers
++
++ - <a href="#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
++ - <a href="#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
++ - <a href="#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
++ - <a href="#api_nan_export"><b><code>Nan::Export()</code></b></a>
++
++<a name="api_nan_asyncresource"></a>
++### Nan::AsyncResource
++
++This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API.
++
++When calling back into JavaScript asynchronously, special care must be taken to ensure that the runtime can properly track
++async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`,
++and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or
++`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms
++such as domains and [async_hooks][] function correctly.
++
++Definition:
++
++```c++
++class AsyncResource {
++ public:
++  AsyncResource(v8::Local<v8::String> name,
++                v8::Local<v8::Object> resource = New<v8::Object>());
++  AsyncResource(const char* name,
++                v8::Local<v8::Object> resource = New<v8::Object>());
++  ~AsyncResource();
++
++  v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
++                                            v8::Local<v8::Function> func,
++                                            int argc,
++                                            v8::Local<v8::Value>* argv);
++  v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
++                                            v8::Local<v8::String> symbol,
++                                            int argc,
++                                            v8::Local<v8::Value>* argv);
++  v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
++                                            const char* method,
++                                            int argc,
++                                            v8::Local<v8::Value>* argv);
++};
++```
++
++* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][]
++  API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend
++  that the name include the name of the owning module as a prefix. For example `mysql` module could use something like
++  `mysql:batch-db-query-resource`.
++* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][]
++  `init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically.
++* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the
++  correct async execution context.
++* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed.
++
++For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the
++[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory.
++
++<a name="api_nan_make_callback"></a>
++### Nan::MakeCallback()
++
++Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+
++has deprecated these legacy APIs as they do not provide a mechanism to preserve
++async context.
++
++We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or
++`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution
++context – something that is essential for functionality like domains, async_hooks and async debugging.
++
++Signatures:
++
++```c++
++NAN_DEPRECATED
++v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
++                                       v8::Local<v8::Function> func,
++                                       int argc,
++                                       v8::Local<v8::Value>* argv);
++NAN_DEPRECATED
++v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
++                                       v8::Local<v8::String> symbol,
++                                       int argc,
++                                       v8::Local<v8::Value>* argv);
++NAN_DEPRECATED
++v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
++                                       const char* method,
++                                       int argc,
++                                       v8::Local<v8::Value>* argv);
++```
++
++
++<a name="api_nan_module_init"></a>
++### NAN_MODULE_INIT()
++
++Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object.
++
++See example below.
++
++<a name="api_nan_export"></a>
++### Nan::Export()
++
++A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript.
++
++Signature:
++
++```c++
++void Export(v8::Local<v8::Object> target, const char *name, Nan::FunctionCallback f)
++```
++
++Also available as the shortcut `NAN_EXPORT` macro.
++
++Example:
++
++```c++
++NAN_METHOD(Foo) {
++  ...
++}
++
++NAN_MODULE_INIT(Init) {
++  NAN_EXPORT(target, Foo);
++}
++```
++
++[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html
++[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..08dd6b5529824646bcf9febe4b94c8f7022d15b9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,263 @@@
++## Object Wrappers
++
++The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
++
++ - <a href="#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
++
++
++<a name="api_nan_object_wrap"></a>
++### Nan::ObjectWrap()
++
++A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency.
++
++Definition:
++
++```c++
++class ObjectWrap {
++ public:
++  ObjectWrap();
++
++  virtual ~ObjectWrap();
++
++  template <class T>
++  static inline T* Unwrap(v8::Local<v8::Object> handle);
++
++  inline v8::Local<v8::Object> handle();
++
++  inline Nan::Persistent<v8::Object>& persistent();
++
++ protected:
++  inline void Wrap(v8::Local<v8::Object> handle);
++
++  inline void MakeWeak();
++
++  /* Ref() marks the object as being attached to an event loop.
++   * Refed objects will not be garbage collected, even if
++   * all references are lost.
++   */
++  virtual void Ref();
++
++  /* Unref() marks an object as detached from the event loop.  This is its
++   * default state.  When an object with a "weak" reference changes from
++   * attached to detached state it will be freed. Be careful not to access
++   * the object after making this call as it might be gone!
++   * (A "weak reference" means an object that only has a
++   * persistant handle.)
++   *
++   * DO NOT CALL THIS FROM DESTRUCTOR
++   */
++  virtual void Unref();
++
++  int refs_;  // ro
++};
++```
++
++See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details.
++
++### This vs. Holder
++
++When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class.
++The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance.
++In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected.
++However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain.
++In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption.
++
++On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype.
++So either define your accessors on the instance template,
++or use `This()` after verifying that it is indeed a valid object.
++
++### Examples
++
++#### Basic
++
++```c++
++class MyObject : public Nan::ObjectWrap {
++ public:
++  static NAN_MODULE_INIT(Init) {
++    v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
++    tpl->SetClassName(Nan::New("MyObject").ToLocalChecked());
++    tpl->InstanceTemplate()->SetInternalFieldCount(1);
++
++    Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle);
++    Nan::SetPrototypeMethod(tpl, "getValue", GetValue);
++
++    constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
++    Nan::Set(target, Nan::New("MyObject").ToLocalChecked(),
++      Nan::GetFunction(tpl).ToLocalChecked());
++  }
++
++ private:
++  explicit MyObject(double value = 0) : value_(value) {}
++  ~MyObject() {}
++
++  static NAN_METHOD(New) {
++    if (info.IsConstructCall()) {
++      double value = info[0]->IsUndefined() ? 0 : Nan::To<double>(info[0]).FromJust();
++      MyObject *obj = new MyObject(value);
++      obj->Wrap(info.This());
++      info.GetReturnValue().Set(info.This());
++    } else {
++      const int argc = 1;
++      v8::Local<v8::Value> argv[argc] = {info[0]};
++      v8::Local<v8::Function> cons = Nan::New(constructor());
++      info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
++    }
++  }
++
++  static NAN_METHOD(GetHandle) {
++    MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder());
++    info.GetReturnValue().Set(obj->handle());
++  }
++
++  static NAN_METHOD(GetValue) {
++    MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder());
++    info.GetReturnValue().Set(obj->value_);
++  }
++
++  static inline Nan::Persistent<v8::Function> & constructor() {
++    static Nan::Persistent<v8::Function> my_constructor;
++    return my_constructor;
++  }
++
++  double value_;
++};
++
++NODE_MODULE(objectwrapper, MyObject::Init)
++```
++
++To use in Javascript:
++
++```Javascript
++var objectwrapper = require('bindings')('objectwrapper');
++
++var obj = new objectwrapper.MyObject(5);
++console.log('Should be 5: ' + obj.getValue());
++```
++
++#### Factory of wrapped objects
++
++```c++
++class MyFactoryObject : public Nan::ObjectWrap {
++ public:
++  static NAN_MODULE_INIT(Init) {
++    v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
++    tpl->InstanceTemplate()->SetInternalFieldCount(1);
++
++    Nan::SetPrototypeMethod(tpl, "getValue", GetValue);
++
++    constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
++  }
++
++  static NAN_METHOD(NewInstance) {
++    v8::Local<v8::Function> cons = Nan::New(constructor());
++    double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0;
++    const int argc = 1;
++    v8::Local<v8::Value> argv[1] = {Nan::New(value)};
++    info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
++  }
++
++  // Needed for the next example:
++  inline double value() const {
++    return value_;
++  }
++
++ private:
++  explicit MyFactoryObject(double value = 0) : value_(value) {}
++  ~MyFactoryObject() {}
++
++  static NAN_METHOD(New) {
++    if (info.IsConstructCall()) {
++      double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0;
++      MyFactoryObject * obj = new MyFactoryObject(value);
++      obj->Wrap(info.This());
++      info.GetReturnValue().Set(info.This());
++    } else {
++      const int argc = 1;
++      v8::Local<v8::Value> argv[argc] = {info[0]};
++      v8::Local<v8::Function> cons = Nan::New(constructor());
++      info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
++    }
++  }
++
++  static NAN_METHOD(GetValue) {
++    MyFactoryObject* obj = ObjectWrap::Unwrap<MyFactoryObject>(info.Holder());
++    info.GetReturnValue().Set(obj->value_);
++  }
++
++  static inline Nan::Persistent<v8::Function> & constructor() {
++    static Nan::Persistent<v8::Function> my_constructor;
++    return my_constructor;
++  }
++
++  double value_;
++};
++
++NAN_MODULE_INIT(Init) {
++  MyFactoryObject::Init(target);
++  Nan::Set(target,
++    Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(),
++    Nan::GetFunction(
++      Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked()
++  );
++}
++
++NODE_MODULE(wrappedobjectfactory, Init)
++```
++
++To use in Javascript:
++
++```Javascript
++var wrappedobjectfactory = require('bindings')('wrappedobjectfactory');
++
++var obj = wrappedobjectfactory.newFactoryObjectInstance(10);
++console.log('Should be 10: ' + obj.getValue());
++```
++
++#### Passing wrapped objects around
++
++Use the `MyFactoryObject` class above along with the following:
++
++```c++
++static NAN_METHOD(Sum) {
++  Nan::MaybeLocal<v8::Object> maybe1 = Nan::To<v8::Object>(info[0]);
++  Nan::MaybeLocal<v8::Object> maybe2 = Nan::To<v8::Object>(info[1]);
++
++  // Quick check:
++  if (maybe1.IsEmpty() || maybe2.IsEmpty()) {
++    // return value is undefined by default
++    return;
++  }
++
++  MyFactoryObject* obj1 =
++    Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe1.ToLocalChecked());
++  MyFactoryObject* obj2 =
++    Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe2.ToLocalChecked());
++
++  info.GetReturnValue().Set(Nan::New<v8::Number>(obj1->value() + obj2->value()));
++}
++
++NAN_MODULE_INIT(Init) {
++  MyFactoryObject::Init(target);
++  Nan::Set(target,
++    Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(),
++    Nan::GetFunction(
++      Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked()
++  );
++  Nan::Set(target,
++    Nan::New<v8::String>("sum").ToLocalChecked(),
++    Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Sum)).ToLocalChecked()
++  );
++}
++
++NODE_MODULE(myaddon, Init)
++```
++
++To use in Javascript:
++
++```Javascript
++var myaddon = require('bindings')('myaddon');
++
++var obj1 = myaddon.newFactoryObjectInstance(5);
++var obj2 = myaddon.newFactoryObjectInstance(10);
++console.log('sum of object values: ' + myaddon.sum(obj1, obj2));
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..bec9c3f39d4042ec677e78e7ea9792e3818d39b8
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,296 @@@
++## Persistent references
++
++An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
++
++Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
++
++ - <a href="#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
++ - <a href="#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
++ - <a href="#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
++ - <a href="#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
++ - <a href="#api_nan_global"><b><code>Nan::Global</code></b></a>
++ - <a href="#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
++ - <a href="#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
++
++Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
++
++<a name="api_nan_persistent_base"></a>
++### Nan::PersistentBase & v8::PersistentBase
++
++A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`.
++
++Definition:
++
++_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_
++
++```c++
++template<typename T> class PersistentBase {
++ public:
++  /**
++   * If non-empty, destroy the underlying storage cell
++   */
++  void Reset();
++
++  /**
++   * If non-empty, destroy the underlying storage cell and create a new one with
++   * the contents of another if it is also non-empty
++   */
++  template<typename S> void Reset(const v8::Local<S> &other);
++
++  /**
++   * If non-empty, destroy the underlying storage cell and create a new one with
++   * the contents of another if it is also non-empty
++   */
++  template<typename S> void Reset(const PersistentBase<S> &other);
++
++  /** Returns true if the handle is empty. */
++  bool IsEmpty() const;
++
++  /**
++   * If non-empty, destroy the underlying storage cell
++   * IsEmpty() will return true after this call.
++   */
++  void Empty();
++
++  template<typename S> bool operator==(const PersistentBase<S> &that);
++
++  template<typename S> bool operator==(const v8::Local<S> &that);
++
++  template<typename S> bool operator!=(const PersistentBase<S> &that);
++
++  template<typename S> bool operator!=(const v8::Local<S> &that);
++
++   /**
++   *  Install a finalization callback on this object.
++   *  NOTE: There is no guarantee as to *when* or even *if* the callback is
++   *  invoked. The invocation is performed solely on a best effort basis.
++   *  As always, GC-based finalization should *not* be relied upon for any
++   *  critical form of resource management! At the moment you can either
++   *  specify a parameter for the callback or the location of two internal
++   *  fields in the dying object.
++   */
++  template<typename P>
++  void SetWeak(P *parameter,
++               typename WeakCallbackInfo<P>::Callback callback,
++               WeakCallbackType type);
++
++  void ClearWeak();
++
++  /**
++   * Marks the reference to this object independent. Garbage collector is free
++   * to ignore any object groups containing this object. Weak callback for an
++   * independent handle should not assume that it will be preceded by a global
++   * GC prologue callback or followed by a global GC epilogue callback.
++   */
++  void MarkIndependent() const;
++
++  bool IsIndependent() const;
++
++  /** Checks if the handle holds the only reference to an object. */
++  bool IsNearDeath() const;
++
++  /** Returns true if the handle's reference is weak.  */
++  bool IsWeak() const
++};
++```
++
++See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/node-8.11/d4/dca/classv8_1_1_persistent_base.html) for further information.
++
++**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object:
++
++```c++
++v8::Local<v8::Object> object = Nan::New(persistent);
++```
++
++<a name="api_nan_non_copyable_persistent_traits"></a>
++### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits
++
++Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version.
++
++Definition:
++
++_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
++
++```c++
++template<typename T> class NonCopyablePersistentTraits {
++ public:
++  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
++
++  static const bool kResetInDestructor = false;
++
++  template<typename S, typename M>
++  static void Copy(const Persistent<S, M> &source,
++                   NonCopyablePersistent *dest);
++
++  template<typename O> static void Uncompilable();
++};
++```
++
++See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.11/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information.
++
++<a name="api_nan_copyable_persistent_traits"></a>
++### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits
++
++A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc..
++
++Definition:
++
++_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
++
++```c++
++template<typename T>
++class CopyablePersistentTraits {
++ public:
++  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
++
++  static const bool kResetInDestructor = true;
++
++  template<typename S, typename M>
++  static void Copy(const Persistent<S, M> &source,
++                   CopyablePersistent *dest);
++};
++```
++
++See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.11/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information.
++
++<a name="api_nan_persistent"></a>
++### Nan::Persistent
++
++A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`.
++
++Definition:
++
++```c++
++template<typename T, typename M = NonCopyablePersistentTraits<T> >
++class Persistent;
++
++template<typename T, typename M> class Persistent : public PersistentBase<T> {
++ public:
++ /**
++  * A Persistent with no storage cell.
++  */
++  Persistent();
++
++  /**
++   * Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a
++   * new storage cell is created pointing to the same object, and no flags are
++   * set.
++   */
++  template<typename S> Persistent(v8::Local<S> that);
++
++  /**
++   * Construct a Persistent from a Persistent. When the Persistent is non-empty,
++   * a new storage cell is created pointing to the same object, and no flags are
++   * set.
++   */
++  Persistent(const Persistent &that);
++
++  /**
++   * The copy constructors and assignment operator create a Persistent exactly
++   * as the Persistent constructor, but the Copy function from the traits class
++   * is called, allowing the setting of flags based on the copied Persistent.
++   */
++  Persistent &operator=(const Persistent &that);
++
++  template <typename S, typename M2>
++  Persistent &operator=(const Persistent<S, M2> &that);
++
++  /**
++   * The destructor will dispose the Persistent based on the kResetInDestructor
++   * flags in the traits class.  Since not calling dispose can result in a
++   * memory leak, it is recommended to always set this flag.
++   */
++  ~Persistent();
++};
++```
++
++See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/node-8.11/d2/d78/classv8_1_1_persistent.html) for further information.
++
++<a name="api_nan_global"></a>
++### Nan::Global
++
++A type of `PersistentBase` which has move semantics.
++
++```c++
++template<typename T> class Global : public PersistentBase<T> {
++ public:
++  /**
++   * A Global with no storage cell.
++   */
++  Global();
++
++  /**
++   * Construct a Global from a v8::Local. When the v8::Local is non-empty, a new
++   * storage cell is created pointing to the same object, and no flags are set.
++   */
++  template<typename S> Global(v8::Local<S> that);
++  /**
++   * Construct a Global from a PersistentBase. When the Persistent is non-empty,
++   * a new storage cell is created pointing to the same object, and no flags are
++   * set.
++   */
++  template<typename S> Global(const PersistentBase<S> &that);
++
++  /**
++   * Pass allows returning globals from functions, etc.
++   */
++  Global Pass();
++};
++```
++
++See the V8 documentation for [`Global`](https://v8docs.nodesource.com/node-8.11/d5/d40/classv8_1_1_global.html) for further information.
++
++<a name="api_nan_weak_callback_info"></a>
++### Nan::WeakCallbackInfo
++
++`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8.
++
++Definition:
++
++```c++
++template<typename T> class WeakCallbackInfo {
++ public:
++  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
++
++  v8::Isolate *GetIsolate() const;
++
++  /**
++   * Get the parameter that was associated with the weak handle.
++   */
++  T *GetParameter() const;
++
++  /**
++   * Get pointer from internal field, index can be 0 or 1.
++   */
++  void *GetInternalField(int index) const;
++};
++```
++
++Example usage:
++
++```c++
++void weakCallback(const WeakCallbackInfo<int> &data) {
++  int *parameter = data.GetParameter();
++  delete parameter;
++}
++
++Persistent<v8::Object> obj;
++int *data = new int(0);
++obj.SetWeak(data, callback, WeakCallbackType::kParameter);
++```
++
++See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/node-8.11/d8/d06/classv8_1_1_weak_callback_info.html) for further information.
++
++<a name="api_nan_weak_callback_type"></a>
++### Nan::WeakCallbackType
++
++Represents the type of a weak callback.
++A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`.
++A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase<v8::Object>` being made weak.
++Note that only `v8::Object`s and derivatives can have internal fields.
++
++Definition:
++
++```c++
++enum class WeakCallbackType { kParameter, kInternalFields };
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..27ab863095a2f63c7a13ea917fefd53ab3d2dbb3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,73 @@@
++## Scopes
++
++A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
++
++A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
++
++The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
++
++ - <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
++ - <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
++
++Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
++
++<a name="api_nan_handle_scope"></a>
++### Nan::HandleScope
++
++A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/node-8.11/d3/d95/classv8_1_1_handle_scope.html).
++
++Definition:
++
++```c++
++class Nan::HandleScope {
++ public:
++  Nan::HandleScope();
++  static int NumberOfHandles();
++};
++```
++
++Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself.
++
++Example:
++
++```c++
++// new object is created, it needs a new scope:
++void Pointless() {
++  Nan::HandleScope scope;
++  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
++}
++
++// JavaScript-accessible method already has a HandleScope
++NAN_METHOD(Pointless2) {
++  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
++}
++```
++
++<a name="api_nan_escapable_handle_scope"></a>
++### Nan::EscapableHandleScope
++
++Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it.
++
++Definition:
++
++```c++
++class Nan::EscapableHandleScope {
++ public:
++  Nan::EscapableHandleScope();
++  static int NumberOfHandles();
++  template<typename T> v8::Local<T> Escape(v8::Local<T> value);
++}
++```
++
++Use `Escape(value)` to return the object.
++
++Example:
++
++```c++
++v8::Local<v8::Object> EmptyObj() {
++  Nan::EscapableHandleScope scope;
++  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
++  return scope.Escape(obj);
++}
++```
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..945398f04e58c18772dbfb55260b95ba3de199ec
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,38 @@@
++## Script
++
++NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
++
++ - <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
++ - <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
++
++
++<a name="api_nan_compile_script"></a>
++### Nan::CompileScript()
++
++A wrapper around [`v8::ScriptCompiler::Compile()`](https://v8docs.nodesource.com/node-8.11/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b).
++
++Note that `Nan::BoundScript` is an alias for `v8::Script`.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(
++    v8::Local<v8::String> s,
++    const v8::ScriptOrigin& origin);
++Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s);
++```
++
++
++<a name="api_nan_run_script"></a>
++### Nan::RunScript()
++
++Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`.
++
++Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8.
++
++Signature:
++
++```c++
++Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script)
++Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script) 
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7c1bd3250476b6b16a29ff684a3a7f86de26a7f9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,62 @@@
++## Strings & Bytes
++
++Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
++
++ - <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
++ - <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
++ - <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
++ - <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
++
++
++<a name="api_nan_encoding"></a>
++### Nan::Encoding
++
++An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node.
++
++Definition:
++
++```c++
++enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER }
++```
++
++
++<a name="api_nan_encode"></a>
++### Nan::Encode()
++
++A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node.
++
++Signature:
++
++```c++
++v8::Local<v8::Value> Nan::Encode(const void *buf,
++                                 size_t len,
++                                 enum Nan::Encoding encoding = BINARY);
++```
++
++
++<a name="api_nan_decode_bytes"></a>
++### Nan::DecodeBytes()
++
++A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node.
++
++Signature:
++
++```c++
++ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val,
++                         enum Nan::Encoding encoding = BINARY);
++```
++
++
++<a name="api_nan_decode_write"></a>
++### Nan::DecodeWrite()
++
++A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node.
++
++Signature:
++
++```c++
++ssize_t Nan::DecodeWrite(char *buf,
++                         size_t len,
++                         v8::Local<v8::Value> val,
++                         enum Nan::Encoding encoding = BINARY);
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..88bd2deb0e009bc10911fe624d03cf5d6db04114
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,199 @@@
++## V8 internals
++
++The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
++
++ - <a href="#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
++ - <a href="#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
++ - <a href="#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
++ - <a href="#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
++ - <a href="#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
++ - <a href="#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
++ - <a href="#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
++ - <a href="#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
++ - <a href="#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
++ - <a href="#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
++ - <a href="#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
++ - <a href="#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
++ - <a href="#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
++ - <a href="#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
++ - <a href="#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
++
++
++<a name="api_nan_gc_callback"></a>
++### NAN_GC_CALLBACK(callbackname)
++
++Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`.
++
++```c++
++static Nan::Persistent<Function> callback;
++
++NAN_GC_CALLBACK(gcPrologueCallback) {
++  v8::Local<Value> argv[] = { Nan::New("prologue").ToLocalChecked() };
++  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv);
++}
++
++NAN_METHOD(Hook) {
++  callback.Reset(To<Function>(args[0]).ToLocalChecked());
++  Nan::AddGCPrologueCallback(gcPrologueCallback);
++  info.GetReturnValue().Set(info.Holder());
++}
++```
++
++<a name="api_nan_add_gc_epilogue_callback"></a>
++### Nan::AddGCEpilogueCallback()
++
++Signature:
++
++```c++
++void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll)
++```
++
++Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a580f976e4290cead62c2fc4dd396be3e).
++
++<a name="api_nan_remove_gc_epilogue_callback"></a>
++### Nan::RemoveGCEpilogueCallback()
++
++Signature:
++
++```c++
++void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback)
++```
++
++Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#adca9294555a3908e9f23c7bb0f0f284c).
++
++<a name="api_nan_add_gc_prologue_callback"></a>
++### Nan::AddGCPrologueCallback()
++
++Signature:
++
++```c++
++void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback)
++```
++
++Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a6dbef303603ebdb03da6998794ea05b8).
++
++<a name="api_nan_remove_gc_prologue_callback"></a>
++### Nan::RemoveGCPrologueCallback()
++
++Signature:
++
++```c++
++void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback)
++```
++
++Calls V8's [`RemoveGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a5f72c7cda21415ce062bbe5c58abe09e).
++
++<a name="api_nan_get_heap_statistics"></a>
++### Nan::GetHeapStatistics()
++
++Signature:
++
++```c++
++void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics)
++```
++
++Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34).
++
++<a name="api_nan_set_counter_function"></a>
++### Nan::SetCounterFunction()
++
++Signature:
++
++```c++
++void Nan::SetCounterFunction(v8::CounterLookupCallback cb)
++```
++
++Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94).
++
++<a name="api_nan_set_create_histogram_function"></a>
++### Nan::SetCreateHistogramFunction()
++
++Signature:
++
++```c++
++void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb) 
++```
++
++Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732).
++
++<a name="api_nan_set_add_histogram_sample_function"></a>
++### Nan::SetAddHistogramSampleFunction()
++
++Signature:
++
++```c++
++void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) 
++```
++
++Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea).
++
++<a name="api_nan_idle_notification"></a>
++### Nan::IdleNotification()
++
++Signature:
++
++```c++
++bool Nan::IdleNotification(int idle_time_in_ms)
++```
++
++Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version.
++
++<a name="api_nan_low_memory_notification"></a>
++### Nan::LowMemoryNotification()
++
++Signature:
++
++```c++
++void Nan::LowMemoryNotification() 
++```
++
++Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f).
++
++<a name="api_nan_context_disposed_notification"></a>
++### Nan::ContextDisposedNotification()
++
++Signature:
++
++```c++
++void Nan::ContextDisposedNotification()
++```
++
++Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b).
++
++<a name="api_nan_get_internal_field_pointer"></a>
++### Nan::GetInternalFieldPointer()
++
++Gets a pointer to the internal field with at `index` from a V8 `Object` handle.
++
++Signature:
++
++```c++
++void* Nan::GetInternalFieldPointer(v8::Local<v8::Object> object, int index) 
++```
++
++Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a580ea84afb26c005d6762eeb9e3c308f) depending on the version of V8.
++
++<a name="api_nan_set_internal_field_pointer"></a>
++### Nan::SetInternalFieldPointer()
++
++Sets the value of the internal field at `index` on a V8 `Object` handle.
++
++Signature:
++
++```c++
++void Nan::SetInternalFieldPointer(v8::Local<v8::Object> object, int index, void* value)
++```
++
++Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8.
++
++<a name="api_nan_adjust_external_memory"></a>
++### Nan::AdjustExternalMemory()
++
++Signature:
++
++```c++
++int Nan::AdjustExternalMemory(int bytesChange)
++```
++
++Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e).
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8e2db20d0fe560817ce1448dfc30fda6e505872d
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,85 @@@
++## Miscellaneous V8 Helpers
++
++ - <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
++ - <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
++ - <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
++ - <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
++ - <a href="#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
++
++
++<a name="api_nan_utf8_string"></a>
++### Nan::Utf8String
++
++Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object.
++
++An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/node-8.11/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8.
++
++Definition:
++
++```c++
++class Nan::Utf8String {
++ public:
++  Nan::Utf8String(v8::Local<v8::Value> from);
++
++  int length() const;
++
++  char* operator*();
++  const char* operator*() const;
++};
++```
++
++<a name="api_nan_get_current_context"></a>
++### Nan::GetCurrentContext()
++
++A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8.
++
++Signature:
++
++```c++
++v8::Local<v8::Context> Nan::GetCurrentContext()
++```
++
++<a name="api_nan_set_isolate_data"></a>
++### Nan::SetIsolateData()
++
++A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36).
++
++Signature:
++
++```c++
++void Nan::SetIsolateData(v8::Isolate *isolate, T *data)
++```
++
++
++<a name="api_nan_get_isolate_data"></a>
++### Nan::GetIsolateData()
++
++A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257).
++
++Signature:
++
++```c++
++T *Nan::GetIsolateData(v8::Isolate *isolate)
++```
++
++<a name="api_nan_typedarray_contents"></a>
++### Nan::TypedArrayContents<T>
++
++A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++.  If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0.  If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail.
++
++Note that you must store a reference to the `array` object while you are accessing its contents.
++
++Definition:
++
++```c++
++template<typename T>
++class Nan::TypedArrayContents {
++ public:
++  TypedArrayContents(v8::Local<Value> array);
++
++  size_t length() const;
++
++  T* const operator*();
++  const T* const operator*() const;
++};
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4f1dfb41667b9b86b4db9bb2255eaef5ab1b9ab6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,1 @@@
++console.log(require('path').relative('.', __dirname));
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..514115d9808df6b356e21878510025e7f897aedc
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,2892 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors:
++ *   - Rod Vagg <https://github.com/rvagg>
++ *   - Benjamin Byholm <https://github.com/kkoopa>
++ *   - Trevor Norris <https://github.com/trevnorris>
++ *   - Nathan Rajlich <https://github.com/TooTallNate>
++ *   - Brett Lawson <https://github.com/brett19>
++ *   - Ben Noordhuis <https://github.com/bnoordhuis>
++ *   - David Siegel <https://github.com/agnat>
++ *   - Michael Ira Krufky <https://github.com/mkrufky>
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ *
++ * Version 2.14.0: current Node 12.2.0, Node 12: 0.12.18, Node 10: 0.10.48, iojs: 3.3.1
++ *
++ * See https://github.com/nodejs/nan for the latest update to this file
++ **********************************************************************************/
++
++#ifndef NAN_H_
++#define NAN_H_
++
++#include <node_version.h>
++
++#define NODE_0_10_MODULE_VERSION 11
++#define NODE_0_12_MODULE_VERSION 14
++#define ATOM_0_21_MODULE_VERSION 41
++#define IOJS_1_0_MODULE_VERSION  42
++#define IOJS_1_1_MODULE_VERSION  43
++#define IOJS_2_0_MODULE_VERSION  44
++#define IOJS_3_0_MODULE_VERSION  45
++#define NODE_4_0_MODULE_VERSION  46
++#define NODE_5_0_MODULE_VERSION  47
++#define NODE_6_0_MODULE_VERSION  48
++#define NODE_7_0_MODULE_VERSION  51
++#define NODE_8_0_MODULE_VERSION  57
++#define NODE_9_0_MODULE_VERSION  59
++#define NODE_10_0_MODULE_VERSION 64
++#define NODE_11_0_MODULE_VERSION 67
++#define NODE_12_0_MODULE_VERSION 72
++
++#ifdef _MSC_VER
++# define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800)
++#else
++# define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L)
++#endif
++
++#if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11
++# error This version of node/NAN/v8 requires a C++11 compiler
++#endif
++
++#include <uv.h>
++#include <node.h>
++#include <node_buffer.h>
++#include <node_object_wrap.h>
++#include <algorithm>
++#include <cstring>
++#include <climits>
++#include <cstdlib>
++#include <utility>
++#if defined(_MSC_VER)
++# pragma warning( push )
++# pragma warning( disable : 4530 )
++# include <queue>
++# include <string>
++# include <vector>
++# pragma warning( pop )
++#else
++# include <queue>
++# include <string>
++# include <vector>
++#endif
++
++// uv helpers
++#ifdef UV_VERSION_MAJOR
++# ifndef UV_VERSION_PATCH
++#  define UV_VERSION_PATCH 0
++# endif
++# define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \
++                         (UV_VERSION_MINOR <<  8) | \
++                         (UV_VERSION_PATCH))
++#else
++# define NAUV_UVVERSION 0x000b00
++#endif
++
++#if NAUV_UVVERSION < 0x000b0b
++# ifdef WIN32
++#  include <windows.h>
++# else
++#  include <pthread.h>
++# endif
++#endif
++
++namespace Nan {
++
++#define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b)
++#define NAN_CONCAT_HELPER(a, b) a##b
++
++#define NAN_INLINE inline  // TODO(bnoordhuis) Remove in v3.0.0.
++
++#if defined(__GNUC__) && \
++    !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
++# define NAN_DEPRECATED __attribute__((deprecated))
++#elif defined(_MSC_VER) && \
++    !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
++# define NAN_DEPRECATED __declspec(deprecated)
++#else
++# define NAN_DEPRECATED
++#endif
++
++#if NAN_HAS_CPLUSPLUS_11
++# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
++# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
++# define NAN_DISALLOW_MOVE(CLASS)                                              \
++    CLASS(CLASS&&) = delete;  /* NOLINT(build/c++11) */                        \
++    void operator=(CLASS&&) = delete;
++#else
++# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&);
++# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&);
++# define NAN_DISALLOW_MOVE(CLASS)
++#endif
++
++#define NAN_DISALLOW_ASSIGN_COPY(CLASS)                                        \
++    NAN_DISALLOW_ASSIGN(CLASS)                                                 \
++    NAN_DISALLOW_COPY(CLASS)
++
++#define NAN_DISALLOW_ASSIGN_MOVE(CLASS)                                        \
++    NAN_DISALLOW_ASSIGN(CLASS)                                                 \
++    NAN_DISALLOW_MOVE(CLASS)
++
++#define NAN_DISALLOW_COPY_MOVE(CLASS)                                          \
++    NAN_DISALLOW_COPY(CLASS)                                                   \
++    NAN_DISALLOW_MOVE(CLASS)
++
++#define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS)                                   \
++    NAN_DISALLOW_ASSIGN(CLASS)                                                 \
++    NAN_DISALLOW_COPY(CLASS)                                                   \
++    NAN_DISALLOW_MOVE(CLASS)
++
++#define TYPE_CHECK(T, S)                                                       \
++    while (false) {                                                            \
++      *(static_cast<T *volatile *>(0)) = static_cast<S*>(0);                   \
++    }
++
++//=== RegistrationFunction =====================================================
++
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++  typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
++#else
++  typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
++#endif
++
++#define NAN_MODULE_INIT(name)                                                  \
++    void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target)
++
++#if NODE_MAJOR_VERSION >= 10 || \
++    NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3
++#define NAN_MODULE_WORKER_ENABLED(module_name, registration)                   \
++    extern "C" NODE_MODULE_EXPORT void                                         \
++      NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)(                 \
++        v8::Local<v8::Object> exports, v8::Local<v8::Value> module,            \
++        v8::Local<v8::Context> context)                                        \
++    {                                                                          \
++        registration(exports);                                                 \
++    }
++#else
++#define NAN_MODULE_WORKER_ENABLED(module_name, registration)                   \
++    NODE_MODULE(module_name, registration)
++#endif
++
++//=== CallbackInfo =============================================================
++
++#include "nan_callbacks.h"  // NOLINT(build/include)
++
++//==============================================================================
++
++#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION)
++typedef v8::Script             UnboundScript;
++typedef v8::Script             BoundScript;
++#else
++typedef v8::UnboundScript      UnboundScript;
++typedef v8::Script             BoundScript;
++#endif
++
++#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION)
++typedef v8::String::ExternalAsciiStringResource
++    ExternalOneByteStringResource;
++#else
++typedef v8::String::ExternalOneByteStringResource
++    ExternalOneByteStringResource;
++#endif
++
++#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
++template<typename T>
++class NonCopyablePersistentTraits :
++    public v8::NonCopyablePersistentTraits<T> {};
++template<typename T>
++class CopyablePersistentTraits :
++    public v8::CopyablePersistentTraits<T> {};
++
++template<typename T>
++class PersistentBase :
++    public v8::PersistentBase<T> {};
++
++template<typename T, typename M = v8::NonCopyablePersistentTraits<T> >
++class Persistent;
++#else
++template<typename T> class NonCopyablePersistentTraits;
++template<typename T> class PersistentBase;
++template<typename T, typename P> class WeakCallbackData;
++template<typename T, typename M = NonCopyablePersistentTraits<T> >
++class Persistent;
++#endif  // NODE_MODULE_VERSION
++
++template<typename T>
++class Maybe {
++ public:
++  inline bool IsNothing() const { return !has_value_; }
++  inline bool IsJust() const { return has_value_; }
++
++  inline T ToChecked() const { return FromJust(); }
++  inline void Check() const { FromJust(); }
++
++  inline bool To(T* out) const {
++    if (IsJust()) *out = value_;
++    return IsJust();
++  }
++
++  inline T FromJust() const {
++#if defined(V8_ENABLE_CHECKS)
++    assert(IsJust() && "FromJust is Nothing");
++#endif  // V8_ENABLE_CHECKS
++    return value_;
++  }
++
++  inline T FromMaybe(const T& default_value) const {
++    return has_value_ ? value_ : default_value;
++  }
++
++  inline bool operator==(const Maybe &other) const {
++    return (IsJust() == other.IsJust()) &&
++        (!IsJust() || FromJust() == other.FromJust());
++  }
++
++  inline bool operator!=(const Maybe &other) const {
++    return !operator==(other);
++  }
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++  // Allow implicit conversions from v8::Maybe<T> to Nan::Maybe<T>.
++  Maybe(const v8::Maybe<T>& that)  // NOLINT(runtime/explicit)
++    : has_value_(that.IsJust())
++    , value_(that.FromMaybe(T())) {}
++#endif
++
++ private:
++  Maybe() : has_value_(false) {}
++  explicit Maybe(const T& t) : has_value_(true), value_(t) {}
++  bool has_value_;
++  T value_;
++
++  template<typename U>
++  friend Maybe<U> Nothing();
++  template<typename U>
++  friend Maybe<U> Just(const U& u);
++};
++
++template<typename T>
++inline Maybe<T> Nothing() {
++  return Maybe<T>();
++}
++
++template<typename T>
++inline Maybe<T> Just(const T& t) {
++  return Maybe<T>(t);
++}
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++# include "nan_maybe_43_inl.h"  // NOLINT(build/include)
++#else
++# include "nan_maybe_pre_43_inl.h"  // NOLINT(build/include)
++#endif
++
++#include "nan_converters.h"  // NOLINT(build/include)
++#include "nan_new.h"  // NOLINT(build/include)
++
++#if NAUV_UVVERSION < 0x000b17
++#define NAUV_WORK_CB(func) \
++    void func(uv_async_t *async, int)
++#else
++#define NAUV_WORK_CB(func) \
++    void func(uv_async_t *async)
++#endif
++
++#if NAUV_UVVERSION >= 0x000b0b
++
++typedef uv_key_t nauv_key_t;
++
++inline int nauv_key_create(nauv_key_t *key) {
++  return uv_key_create(key);
++}
++
++inline void nauv_key_delete(nauv_key_t *key) {
++  uv_key_delete(key);
++}
++
++inline void* nauv_key_get(nauv_key_t *key) {
++  return uv_key_get(key);
++}
++
++inline void nauv_key_set(nauv_key_t *key, void *value) {
++  uv_key_set(key, value);
++}
++
++#else
++
++/* Implement thread local storage for older versions of libuv.
++ * This is essentially a backport of libuv commit 5d2434bf
++ * written by Ben Noordhuis, adjusted for names and inline.
++ */
++
++#ifndef WIN32
++
++typedef pthread_key_t nauv_key_t;
++
++inline int nauv_key_create(nauv_key_t* key) {
++  return -pthread_key_create(key, NULL);
++}
++
++inline void nauv_key_delete(nauv_key_t* key) {
++  if (pthread_key_delete(*key))
++    abort();
++}
++
++inline void* nauv_key_get(nauv_key_t* key) {
++  return pthread_getspecific(*key);
++}
++
++inline void nauv_key_set(nauv_key_t* key, void* value) {
++  if (pthread_setspecific(*key, value))
++    abort();
++}
++
++#else
++
++typedef struct {
++  DWORD tls_index;
++} nauv_key_t;
++
++inline int nauv_key_create(nauv_key_t* key) {
++  key->tls_index = TlsAlloc();
++  if (key->tls_index == TLS_OUT_OF_INDEXES)
++    return UV_ENOMEM;
++  return 0;
++}
++
++inline void nauv_key_delete(nauv_key_t* key) {
++  if (TlsFree(key->tls_index) == FALSE)
++    abort();
++  key->tls_index = TLS_OUT_OF_INDEXES;
++}
++
++inline void* nauv_key_get(nauv_key_t* key) {
++  void* value = TlsGetValue(key->tls_index);
++  if (value == NULL)
++    if (GetLastError() != ERROR_SUCCESS)
++      abort();
++  return value;
++}
++
++inline void nauv_key_set(nauv_key_t* key, void* value) {
++  if (TlsSetValue(key->tls_index, value) == FALSE)
++    abort();
++}
++
++#endif
++#endif
++
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++template<typename T>
++v8::Local<T> New(v8::Handle<T>);
++#endif
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++  typedef v8::WeakCallbackType WeakCallbackType;
++#else
++struct WeakCallbackType {
++  enum E {kParameter, kInternalFields};
++  E type;
++  WeakCallbackType(E other) : type(other) {}  // NOLINT(runtime/explicit)
++  inline bool operator==(E other) { return other == this->type; }
++  inline bool operator!=(E other) { return !operator==(other); }
++};
++#endif
++
++template<typename P> class WeakCallbackInfo;
++
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++# include "nan_persistent_12_inl.h"  // NOLINT(build/include)
++#else
++# include "nan_persistent_pre_12_inl.h"  // NOLINT(build/include)
++#endif
++
++namespace imp {
++  static const size_t kMaxLength = 0x3fffffff;
++  // v8::String::REPLACE_INVALID_UTF8 was introduced
++  // in node.js v0.10.29 and v0.8.27.
++#if NODE_MAJOR_VERSION > 0 || \
++    NODE_MINOR_VERSION > 10 || \
++    NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \
++    NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27
++  static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
++#else
++  static const unsigned kReplaceInvalidUtf8 = 0;
++#endif
++}  // end of namespace imp
++
++//=== HandleScope ==============================================================
++
++class HandleScope {
++  v8::HandleScope scope;
++
++ public:
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  inline HandleScope() : scope(v8::Isolate::GetCurrent()) {}
++  inline static int NumberOfHandles() {
++    return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
++  }
++#else
++  inline HandleScope() : scope() {}
++  inline static int NumberOfHandles() {
++    return v8::HandleScope::NumberOfHandles();
++  }
++#endif
++
++ private:
++  // Make it hard to create heap-allocated or illegal handle scopes by
++  // disallowing certain operations.
++  HandleScope(const HandleScope &);
++  void operator=(const HandleScope &);
++  void *operator new(size_t size);
++  void operator delete(void *, size_t) {
++    abort();
++  }
++};
++
++class EscapableHandleScope {
++ public:
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {}
++
++  inline static int NumberOfHandles() {
++    return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
++  }
++
++  template<typename T>
++  inline v8::Local<T> Escape(v8::Local<T> value) {
++    return scope.Escape(value);
++  }
++
++ private:
++  v8::EscapableHandleScope scope;
++#else
++  inline EscapableHandleScope() : scope() {}
++
++  inline static int NumberOfHandles() {
++    return v8::HandleScope::NumberOfHandles();
++  }
++
++  template<typename T>
++  inline v8::Local<T> Escape(v8::Local<T> value) {
++    return scope.Close(value);
++  }
++
++ private:
++  v8::HandleScope scope;
++#endif
++
++ private:
++  // Make it hard to create heap-allocated or illegal handle scopes by
++  // disallowing certain operations.
++  EscapableHandleScope(const EscapableHandleScope &);
++  void operator=(const EscapableHandleScope &);
++  void *operator new(size_t size);
++  void operator delete(void *, size_t) {
++    abort();
++  }
++};
++
++//=== TryCatch =================================================================
++
++class TryCatch {
++  v8::TryCatch try_catch_;
++  friend void FatalException(const TryCatch&);
++
++ public:
++#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++  TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {}
++#endif
++
++  inline bool HasCaught() const { return try_catch_.HasCaught(); }
++
++  inline bool CanContinue() const { return try_catch_.CanContinue(); }
++
++  inline v8::Local<v8::Value> ReThrow() {
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    return New(try_catch_.ReThrow());
++#else
++    return try_catch_.ReThrow();
++#endif
++  }
++
++  inline v8::Local<v8::Value> Exception() const {
++    return try_catch_.Exception();
++  }
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++  inline v8::MaybeLocal<v8::Value> StackTrace() const {
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++    return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext())
++                            .FromMaybe(v8::Local<v8::Value>()));
++  }
++#else
++  inline MaybeLocal<v8::Value> StackTrace() const {
++    return try_catch_.StackTrace();
++  }
++#endif
++
++  inline v8::Local<v8::Message> Message() const {
++    return try_catch_.Message();
++  }
++
++  inline void Reset() { try_catch_.Reset(); }
++
++  inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); }
++
++  inline void SetCaptureMessage(bool value) {
++    try_catch_.SetCaptureMessage(value);
++  }
++};
++
++v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
++                                  v8::Local<v8::Function> func,
++                                  int argc,
++                                  v8::Local<v8::Value>* argv);
++v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
++                                  v8::Local<v8::String> symbol,
++                                  int argc,
++                                  v8::Local<v8::Value>* argv);
++v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
++                                  const char* method,
++                                  int argc,
++                                  v8::Local<v8::Value>* argv);
++
++// === AsyncResource ===========================================================
++
++class AsyncResource {
++ public:
++  AsyncResource(
++      v8::Local<v8::String> name
++    , v8::Local<v8::Object> resource = New<v8::Object>()) {
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    v8::Isolate* isolate = v8::Isolate::GetCurrent();
++
++    if (resource.IsEmpty()) {
++      resource = New<v8::Object>();
++    }
++
++    context = node::EmitAsyncInit(isolate, resource, name);
++#endif
++  }
++
++  AsyncResource(
++      const char* name
++    , v8::Local<v8::Object> resource = New<v8::Object>()) {
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    v8::Isolate* isolate = v8::Isolate::GetCurrent();
++
++    if (resource.IsEmpty()) {
++      resource = New<v8::Object>();
++    }
++
++    v8::Local<v8::String> name_string =
++        New<v8::String>(name).ToLocalChecked();
++    context = node::EmitAsyncInit(isolate, resource, name_string);
++#endif
++  }
++
++  ~AsyncResource() {
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    v8::Isolate* isolate = v8::Isolate::GetCurrent();
++    node::EmitAsyncDestroy(isolate, context);
++#endif
++  }
++
++  inline MaybeLocal<v8::Value> runInAsyncScope(
++      v8::Local<v8::Object> target
++    , v8::Local<v8::Function> func
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
++    return MakeCallback(target, func, argc, argv);
++#else
++    return node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, func, argc, argv, context);
++#endif
++  }
++
++  inline MaybeLocal<v8::Value> runInAsyncScope(
++      v8::Local<v8::Object> target
++    , v8::Local<v8::String> symbol
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
++    return MakeCallback(target, symbol, argc, argv);
++#else
++    return node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, symbol, argc, argv, context);
++#endif
++  }
++
++  inline MaybeLocal<v8::Value> runInAsyncScope(
++      v8::Local<v8::Object> target
++    , const char* method
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
++    return MakeCallback(target, method, argc, argv);
++#else
++    return node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, method, argc, argv, context);
++#endif
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource)
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++  node::async_context context;
++#endif
++};
++
++inline uv_loop_t* GetCurrentEventLoop() {
++#if NODE_MAJOR_VERSION >= 10 || \
++  NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \
++  NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10
++    return node::GetCurrentEventLoop(v8::Isolate::GetCurrent());
++#else
++    return uv_default_loop();
++#endif
++}
++
++//============ =================================================================
++
++/* node 0.12  */
++#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
++  inline
++  void SetCounterFunction(v8::CounterLookupCallback cb) {
++    v8::Isolate::GetCurrent()->SetCounterFunction(cb);
++  }
++
++  inline
++  void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
++    v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb);
++  }
++
++  inline
++  void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
++    v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb);
++  }
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++  inline bool IdleNotification(int idle_time_in_ms) {
++    return v8::Isolate::GetCurrent()->IdleNotificationDeadline(
++        idle_time_in_ms * 0.001);
++  }
++# else
++  inline bool IdleNotification(int idle_time_in_ms) {
++    return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms);
++  }
++#endif
++
++  inline void LowMemoryNotification() {
++    v8::Isolate::GetCurrent()->LowMemoryNotification();
++  }
++
++  inline void ContextDisposedNotification() {
++    v8::Isolate::GetCurrent()->ContextDisposedNotification();
++  }
++#else
++  inline
++  void SetCounterFunction(v8::CounterLookupCallback cb) {
++    v8::V8::SetCounterFunction(cb);
++  }
++
++  inline
++  void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
++    v8::V8::SetCreateHistogramFunction(cb);
++  }
++
++  inline
++  void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
++    v8::V8::SetAddHistogramSampleFunction(cb);
++  }
++
++  inline bool IdleNotification(int idle_time_in_ms) {
++    return v8::V8::IdleNotification(idle_time_in_ms);
++  }
++
++  inline void LowMemoryNotification() {
++    v8::V8::LowMemoryNotification();
++  }
++
++  inline void ContextDisposedNotification() {
++    v8::V8::ContextDisposedNotification();
++  }
++#endif
++
++#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)  // Node 0.12
++  inline v8::Local<v8::Primitive> Undefined() {
++# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent())));
++# else
++    return v8::Undefined(v8::Isolate::GetCurrent());
++# endif
++  }
++
++  inline v8::Local<v8::Primitive> Null() {
++# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent())));
++# else
++    return v8::Null(v8::Isolate::GetCurrent());
++# endif
++  }
++
++  inline v8::Local<v8::Boolean> True() {
++# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::True(v8::Isolate::GetCurrent())));
++# else
++    return v8::True(v8::Isolate::GetCurrent());
++# endif
++  }
++
++  inline v8::Local<v8::Boolean> False() {
++# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::False(v8::Isolate::GetCurrent())));
++# else
++    return v8::False(v8::Isolate::GetCurrent());
++# endif
++  }
++
++  inline v8::Local<v8::String> EmptyString() {
++    return v8::String::Empty(v8::Isolate::GetCurrent());
++  }
++
++  inline int AdjustExternalMemory(int bc) {
++    return static_cast<int>(
++        v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc));
++  }
++
++  inline void SetTemplate(
++      v8::Local<v8::Template> templ
++    , const char *name
++    , v8::Local<v8::Data> value) {
++    templ->Set(v8::Isolate::GetCurrent(), name, value);
++  }
++
++  inline void SetTemplate(
++      v8::Local<v8::Template> templ
++    , v8::Local<v8::String> name
++    , v8::Local<v8::Data> value
++    , v8::PropertyAttribute attributes) {
++    templ->Set(name, value, attributes);
++  }
++
++  inline v8::Local<v8::Context> GetCurrentContext() {
++    return v8::Isolate::GetCurrent()->GetCurrentContext();
++  }
++
++  inline void* GetInternalFieldPointer(
++      v8::Local<v8::Object> object
++    , int index) {
++    return object->GetAlignedPointerFromInternalField(index);
++  }
++
++  inline void SetInternalFieldPointer(
++      v8::Local<v8::Object> object
++    , int index
++    , void* value) {
++    object->SetAlignedPointerInInternalField(index, value);
++  }
++
++# define NAN_GC_CALLBACK(name)                                                 \
++    void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags)
++
++#if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION
++  typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback;
++  typedef v8::Isolate::GCPrologueCallback GCPrologueCallback;
++#else
++  typedef v8::Isolate::GCCallback GCEpilogueCallback;
++  typedef v8::Isolate::GCCallback GCPrologueCallback;
++#endif
++
++  inline void AddGCEpilogueCallback(
++      GCEpilogueCallback callback
++    , v8::GCType gc_type_filter = v8::kGCTypeAll) {
++    v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter);
++  }
++
++  inline void RemoveGCEpilogueCallback(
++      GCEpilogueCallback callback) {
++    v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback);
++  }
++
++  inline void AddGCPrologueCallback(
++      GCPrologueCallback callback
++    , v8::GCType gc_type_filter = v8::kGCTypeAll) {
++    v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter);
++  }
++
++  inline void RemoveGCPrologueCallback(
++      GCPrologueCallback callback) {
++    v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback);
++  }
++
++  inline void GetHeapStatistics(
++      v8::HeapStatistics *heap_statistics) {
++    v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics);
++  }
++
++# define X(NAME)                                                               \
++    inline v8::Local<v8::Value> NAME(const char *msg) {                        \
++      EscapableHandleScope scope;                                              \
++      return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked()));     \
++    }                                                                          \
++                                                                               \
++    inline                                                                     \
++    v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) {                     \
++      return v8::Exception::NAME(msg);                                         \
++    }                                                                          \
++                                                                               \
++    inline void Throw ## NAME(const char *msg) {                               \
++      HandleScope scope;                                                       \
++      v8::Isolate::GetCurrent()->ThrowException(                               \
++          v8::Exception::NAME(New(msg).ToLocalChecked()));                     \
++    }                                                                          \
++                                                                               \
++    inline void Throw ## NAME(v8::Local<v8::String> msg) {                     \
++      HandleScope scope;                                                       \
++      v8::Isolate::GetCurrent()->ThrowException(                               \
++          v8::Exception::NAME(msg));                                           \
++    }
++
++  X(Error)
++  X(RangeError)
++  X(ReferenceError)
++  X(SyntaxError)
++  X(TypeError)
++
++# undef X
++
++  inline void ThrowError(v8::Local<v8::Value> error) {
++    v8::Isolate::GetCurrent()->ThrowException(error);
++  }
++
++  inline MaybeLocal<v8::Object> NewBuffer(
++      char *data
++    , size_t length
++#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
++    , node::Buffer::FreeCallback callback
++#else
++    , node::smalloc::FreeCallback callback
++#endif
++    , void *hint
++  ) {
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(length <= imp::kMaxLength && "too large buffer");
++#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
++    return node::Buffer::New(
++        v8::Isolate::GetCurrent(), data, length, callback, hint);
++#else
++    return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback,
++                             hint);
++#endif
++  }
++
++  inline MaybeLocal<v8::Object> CopyBuffer(
++      const char *data
++    , uint32_t size
++  ) {
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(size <= imp::kMaxLength && "too large buffer");
++#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
++    return node::Buffer::Copy(
++        v8::Isolate::GetCurrent(), data, size);
++#else
++    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
++#endif
++  }
++
++  inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(size <= imp::kMaxLength && "too large buffer");
++#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
++    return node::Buffer::New(
++        v8::Isolate::GetCurrent(), size);
++#else
++    return node::Buffer::New(v8::Isolate::GetCurrent(), size);
++#endif
++  }
++
++  inline MaybeLocal<v8::Object> NewBuffer(
++      char* data
++    , uint32_t size
++  ) {
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(size <= imp::kMaxLength && "too large buffer");
++#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
++    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
++#else
++    return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
++#endif
++  }
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++  inline MaybeLocal<v8::String>
++  NewOneByteString(const uint8_t * value, int length = -1) {
++    return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
++          v8::NewStringType::kNormal, length);
++  }
++
++  inline MaybeLocal<BoundScript> CompileScript(
++      v8::Local<v8::String> s
++    , const v8::ScriptOrigin& origin
++  ) {
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++    v8::ScriptCompiler::Source source(s, origin);
++    return scope.Escape(
++        v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
++            .FromMaybe(v8::Local<BoundScript>()));
++  }
++
++  inline MaybeLocal<BoundScript> CompileScript(
++      v8::Local<v8::String> s
++  ) {
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++    v8::ScriptCompiler::Source source(s);
++    return scope.Escape(
++        v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
++            .FromMaybe(v8::Local<BoundScript>()));
++  }
++
++  inline MaybeLocal<v8::Value> RunScript(
++      v8::Local<UnboundScript> script
++  ) {
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++    return scope.Escape(script->BindToCurrentContext()
++                            ->Run(isolate->GetCurrentContext())
++                            .FromMaybe(v8::Local<v8::Value>()));
++  }
++
++  inline MaybeLocal<v8::Value> RunScript(
++      v8::Local<BoundScript> script
++  ) {
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++    return scope.Escape(script->Run(isolate->GetCurrentContext())
++                            .FromMaybe(v8::Local<v8::Value>()));
++  }
++#else
++  inline MaybeLocal<v8::String>
++  NewOneByteString(const uint8_t * value, int length = -1) {
++    return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
++                                      v8::String::kNormalString, length);
++  }
++
++  inline MaybeLocal<BoundScript> CompileScript(
++      v8::Local<v8::String> s
++    , const v8::ScriptOrigin& origin
++  ) {
++    v8::ScriptCompiler::Source source(s, origin);
++    return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
++  }
++
++  inline MaybeLocal<BoundScript> CompileScript(
++      v8::Local<v8::String> s
++  ) {
++    v8::ScriptCompiler::Source source(s);
++    return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
++  }
++
++  inline MaybeLocal<v8::Value> RunScript(
++      v8::Local<UnboundScript> script
++  ) {
++    EscapableHandleScope scope;
++    return scope.Escape(script->BindToCurrentContext()->Run());
++  }
++
++  inline MaybeLocal<v8::Value> RunScript(
++      v8::Local<BoundScript> script
++  ) {
++    return script->Run();
++  }
++#endif
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
++      v8::Local<v8::Object> target
++    , v8::Local<v8::Function> func
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, func, argc, argv)));
++#else
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource res("nan:makeCallback");
++    return res.runInAsyncScope(target, func, argc, argv)
++        .FromMaybe(v8::Local<v8::Value>());
++# else
++    return node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, func, argc, argv);
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#endif  // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++  }
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
++      v8::Local<v8::Object> target
++    , v8::Local<v8::String> symbol
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, symbol, argc, argv)));
++#else
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource res("nan:makeCallback");
++    return res.runInAsyncScope(target, symbol, argc, argv)
++        .FromMaybe(v8::Local<v8::Value>());
++# else
++    return node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, symbol, argc, argv);
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#endif  // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++  }
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
++      v8::Local<v8::Object> target
++    , const char* method
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    return scope.Escape(New(node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, method, argc, argv)));
++#else
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource res("nan:makeCallback");
++    return res.runInAsyncScope(target, method, argc, argv)
++        .FromMaybe(v8::Local<v8::Value>());
++# else
++    return node::MakeCallback(
++        v8::Isolate::GetCurrent(), target, method, argc, argv);
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#endif  // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++  }
++
++  inline void FatalException(const TryCatch& try_catch) {
++    node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_);
++  }
++
++  inline v8::Local<v8::Value> ErrnoException(
++          int errorno
++       ,  const char* syscall = NULL
++       ,  const char* message = NULL
++       ,  const char* path = NULL) {
++    return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall,
++            message, path);
++  }
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
++          int errorno
++       ,  const char* syscall = NULL
++       ,  const char* message = NULL
++       ,  const char* path = NULL) {
++    return ErrnoException(errorno, syscall, message, path);
++  }
++
++  template<typename T>
++  inline void SetIsolateData(
++      v8::Isolate *isolate
++    , T *data
++  ) {
++      isolate->SetData(0, data);
++  }
++
++  template<typename T>
++  inline T *GetIsolateData(
++      v8::Isolate *isolate
++  ) {
++      return static_cast<T*>(isolate->GetData(0));
++  }
++
++class Utf8String {
++ public:
++  inline explicit Utf8String(v8::Local<v8::Value> from) :
++      length_(0), str_(str_st_) {
++    HandleScope scope;
++    if (!from.IsEmpty()) {
++#if NODE_MAJOR_VERSION >= 10
++      v8::Local<v8::Context> context = GetCurrentContext();
++      v8::Local<v8::String> string =
++          from->ToString(context).FromMaybe(v8::Local<v8::String>());
++#else
++      v8::Local<v8::String> string = from->ToString();
++#endif
++      if (!string.IsEmpty()) {
++        size_t len = 3 * string->Length() + 1;
++        assert(len <= INT_MAX);
++        if (len > sizeof (str_st_)) {
++          str_ = static_cast<char*>(malloc(len));
++          assert(str_ != 0);
++        }
++        const int flags =
++            v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
++#if NODE_MAJOR_VERSION >= 11
++        length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_,
++                                    static_cast<int>(len), 0, flags);
++#else
++        // See https://github.com/nodejs/nan/issues/832.
++        // Disable the warning as there is no way around it.
++#ifdef _MSC_VER
++#pragma warning(push)
++#pragma warning(disable : 4996)
++#endif
++#ifdef __GNUC__
++#pragma GCC diagnostic push
++#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
++#endif
++        length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
++#ifdef __GNUC__
++#pragma GCC diagnostic pop
++#endif
++#ifdef _MSC_VER
++#pragma warning(pop)
++#endif
++#endif  // NODE_MAJOR_VERSION < 11
++        str_[length_] = '\0';
++      }
++    }
++  }
++
++  inline int length() const {
++    return length_;
++  }
++
++  inline char* operator*() { return str_; }
++  inline const char* operator*() const { return str_; }
++
++  inline ~Utf8String() {
++    if (str_ != str_st_) {
++      free(str_);
++    }
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
++
++  int length_;
++  char *str_;
++  char str_st_[1024];
++};
++
++#else  // Node 0.8 and 0.10
++  inline v8::Local<v8::Primitive> Undefined() {
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::Undefined()));
++  }
++
++  inline v8::Local<v8::Primitive> Null() {
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::Null()));
++  }
++
++  inline v8::Local<v8::Boolean> True() {
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::True()));
++  }
++
++  inline v8::Local<v8::Boolean> False() {
++    EscapableHandleScope scope;
++    return scope.Escape(New(v8::False()));
++  }
++
++  inline v8::Local<v8::String> EmptyString() {
++    return v8::String::Empty();
++  }
++
++  inline int AdjustExternalMemory(int bc) {
++    return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc));
++  }
++
++  inline void SetTemplate(
++      v8::Local<v8::Template> templ
++    , const char *name
++    , v8::Local<v8::Data> value) {
++    templ->Set(name, value);
++  }
++
++  inline void SetTemplate(
++      v8::Local<v8::Template> templ
++    , v8::Local<v8::String> name
++    , v8::Local<v8::Data> value
++    , v8::PropertyAttribute attributes) {
++    templ->Set(name, value, attributes);
++  }
++
++  inline v8::Local<v8::Context> GetCurrentContext() {
++    return v8::Context::GetCurrent();
++  }
++
++  inline void* GetInternalFieldPointer(
++      v8::Local<v8::Object> object
++    , int index) {
++    return object->GetPointerFromInternalField(index);
++  }
++
++  inline void SetInternalFieldPointer(
++      v8::Local<v8::Object> object
++    , int index
++    , void* value) {
++    object->SetPointerInInternalField(index, value);
++  }
++
++# define NAN_GC_CALLBACK(name)                                                 \
++    void name(v8::GCType type, v8::GCCallbackFlags flags)
++
++  inline void AddGCEpilogueCallback(
++    v8::GCEpilogueCallback callback
++  , v8::GCType gc_type_filter = v8::kGCTypeAll) {
++    v8::V8::AddGCEpilogueCallback(callback, gc_type_filter);
++  }
++  inline void RemoveGCEpilogueCallback(
++    v8::GCEpilogueCallback callback) {
++    v8::V8::RemoveGCEpilogueCallback(callback);
++  }
++  inline void AddGCPrologueCallback(
++    v8::GCPrologueCallback callback
++  , v8::GCType gc_type_filter = v8::kGCTypeAll) {
++    v8::V8::AddGCPrologueCallback(callback, gc_type_filter);
++  }
++  inline void RemoveGCPrologueCallback(
++    v8::GCPrologueCallback callback) {
++    v8::V8::RemoveGCPrologueCallback(callback);
++  }
++  inline void GetHeapStatistics(
++    v8::HeapStatistics *heap_statistics) {
++    v8::V8::GetHeapStatistics(heap_statistics);
++  }
++
++# define X(NAME)                                                               \
++    inline v8::Local<v8::Value> NAME(const char *msg) {                        \
++      EscapableHandleScope scope;                                              \
++      return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked()));     \
++    }                                                                          \
++                                                                               \
++    inline                                                                     \
++    v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) {                     \
++      return v8::Exception::NAME(msg);                                         \
++    }                                                                          \
++                                                                               \
++    inline void Throw ## NAME(const char *msg) {                               \
++      HandleScope scope;                                                       \
++      v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked()));      \
++    }                                                                          \
++                                                                               \
++    inline                                                                     \
++    void Throw ## NAME(v8::Local<v8::String> errmsg) {                         \
++      HandleScope scope;                                                       \
++      v8::ThrowException(v8::Exception::NAME(errmsg));                         \
++    }
++
++  X(Error)
++  X(RangeError)
++  X(ReferenceError)
++  X(SyntaxError)
++  X(TypeError)
++
++# undef X
++
++  inline void ThrowError(v8::Local<v8::Value> error) {
++    v8::ThrowException(error);
++  }
++
++  inline MaybeLocal<v8::Object> NewBuffer(
++      char *data
++    , size_t length
++    , node::Buffer::free_callback callback
++    , void *hint
++  ) {
++    EscapableHandleScope scope;
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(length <= imp::kMaxLength && "too large buffer");
++    return scope.Escape(
++        New(node::Buffer::New(data, length, callback, hint)->handle_));
++  }
++
++  inline MaybeLocal<v8::Object> CopyBuffer(
++      const char *data
++    , uint32_t size
++  ) {
++    EscapableHandleScope scope;
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(size <= imp::kMaxLength && "too large buffer");
++#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
++    return scope.Escape(New(node::Buffer::New(data, size)->handle_));
++#else
++    return scope.Escape(
++        New(node::Buffer::New(const_cast<char *>(data), size)->handle_));
++#endif
++  }
++
++  inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    EscapableHandleScope scope;
++    assert(size <= imp::kMaxLength && "too large buffer");
++    return scope.Escape(New(node::Buffer::New(size)->handle_));
++  }
++
++  inline void FreeData(char *data, void *hint) {
++    (void) hint;  // unused
++    delete[] data;
++  }
++
++  inline MaybeLocal<v8::Object> NewBuffer(
++      char* data
++    , uint32_t size
++  ) {
++    EscapableHandleScope scope;
++    // arbitrary buffer lengths requires
++    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
++    assert(size <= imp::kMaxLength && "too large buffer");
++    return scope.Escape(
++        New(node::Buffer::New(data, size, FreeData, NULL)->handle_));
++  }
++
++namespace imp {
++inline void
++widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) {
++  size_t len = static_cast<size_t>(l);
++  if (l < 0) {
++    len = strlen(reinterpret_cast<const char*>(s));
++  }
++  assert(len <= INT_MAX && "string too long");
++  ws->resize(len);
++  std::copy(s, s + len, ws->begin());  // NOLINT(build/include_what_you_use)
++}
++}  // end of namespace imp
++
++  inline MaybeLocal<v8::String>
++  NewOneByteString(const uint8_t * value, int length = -1) {
++    std::vector<uint16_t> wideString;  // NOLINT(build/include_what_you_use)
++    imp::widenString(&wideString, value, length);
++    return v8::String::New(wideString.data(),
++                           static_cast<int>(wideString.size()));
++  }
++
++  inline MaybeLocal<BoundScript> CompileScript(
++      v8::Local<v8::String> s
++    , const v8::ScriptOrigin& origin
++  ) {
++    return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin));
++  }
++
++  inline MaybeLocal<BoundScript> CompileScript(
++    v8::Local<v8::String> s
++  ) {
++    return v8::Script::Compile(s);
++  }
++
++  inline
++  MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) {
++    return script->Run();
++  }
++
++  inline v8::Local<v8::Value> MakeCallback(
++      v8::Local<v8::Object> target
++    , v8::Local<v8::Function> func
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++    v8::HandleScope scope;
++    return scope.Close(New(node::MakeCallback(target, func, argc, argv)));
++  }
++
++  inline v8::Local<v8::Value> MakeCallback(
++      v8::Local<v8::Object> target
++    , v8::Local<v8::String> symbol
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++    v8::HandleScope scope;
++    return scope.Close(New(node::MakeCallback(target, symbol, argc, argv)));
++  }
++
++  inline v8::Local<v8::Value> MakeCallback(
++      v8::Local<v8::Object> target
++    , const char* method
++    , int argc
++    , v8::Local<v8::Value>* argv) {
++    v8::HandleScope scope;
++    return scope.Close(New(node::MakeCallback(target, method, argc, argv)));
++  }
++
++  inline void FatalException(const TryCatch& try_catch) {
++    node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_));
++  }
++
++  inline v8::Local<v8::Value> ErrnoException(
++          int errorno
++       ,  const char* syscall = NULL
++       ,  const char* message = NULL
++       ,  const char* path = NULL) {
++    return node::ErrnoException(errorno, syscall, message, path);
++  }
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
++          int errorno
++       ,  const char* syscall = NULL
++       ,  const char* message = NULL
++       ,  const char* path = NULL) {
++    return ErrnoException(errorno, syscall, message, path);
++  }
++
++
++  template<typename T>
++  inline void SetIsolateData(
++      v8::Isolate *isolate
++    , T *data
++  ) {
++      isolate->SetData(data);
++  }
++
++  template<typename T>
++  inline T *GetIsolateData(
++      v8::Isolate *isolate
++  ) {
++      return static_cast<T*>(isolate->GetData());
++  }
++
++class Utf8String {
++ public:
++  inline explicit Utf8String(v8::Local<v8::Value> from) :
++      length_(0), str_(str_st_) {
++    v8::HandleScope scope;
++    if (!from.IsEmpty()) {
++      v8::Local<v8::String> string = from->ToString();
++      if (!string.IsEmpty()) {
++        size_t len = 3 * string->Length() + 1;
++        assert(len <= INT_MAX);
++        if (len > sizeof (str_st_)) {
++          str_ = static_cast<char*>(malloc(len));
++          assert(str_ != 0);
++        }
++        const int flags =
++            v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
++        length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
++        str_[length_] = '\0';
++      }
++    }
++  }
++
++  inline int length() const {
++    return length_;
++  }
++
++  inline char* operator*() { return str_; }
++  inline const char* operator*() const { return str_; }
++
++  inline ~Utf8String() {
++    if (str_ != str_st_) {
++      free(str_);
++    }
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
++
++  int length_;
++  char *str_;
++  char str_st_[1024];
++};
++
++#endif  // NODE_MODULE_VERSION
++
++typedef void (*FreeCallback)(char *data, void *hint);
++
++typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE;
++typedef void NAN_METHOD_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE;
++typedef void NAN_GETTER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE;
++typedef void NAN_SETTER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Value>&
++    NAN_PROPERTY_GETTER_ARGS_TYPE;
++typedef void NAN_PROPERTY_GETTER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Value>&
++    NAN_PROPERTY_SETTER_ARGS_TYPE;
++typedef void NAN_PROPERTY_SETTER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Array>&
++    NAN_PROPERTY_ENUMERATOR_ARGS_TYPE;
++typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Boolean>&
++    NAN_PROPERTY_DELETER_ARGS_TYPE;
++typedef void NAN_PROPERTY_DELETER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Integer>&
++    NAN_PROPERTY_QUERY_ARGS_TYPE;
++typedef void NAN_PROPERTY_QUERY_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE;
++typedef void NAN_INDEX_GETTER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE;
++typedef void NAN_INDEX_SETTER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Array>&
++    NAN_INDEX_ENUMERATOR_ARGS_TYPE;
++typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Boolean>&
++    NAN_INDEX_DELETER_ARGS_TYPE;
++typedef void NAN_INDEX_DELETER_RETURN_TYPE;
++
++typedef const PropertyCallbackInfo<v8::Integer>&
++    NAN_INDEX_QUERY_ARGS_TYPE;
++typedef void NAN_INDEX_QUERY_RETURN_TYPE;
++
++#define NAN_METHOD(name)                                                       \
++    Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info)
++#define NAN_GETTER(name)                                                       \
++    Nan::NAN_GETTER_RETURN_TYPE name(                                          \
++        v8::Local<v8::String> property                                         \
++      , Nan::NAN_GETTER_ARGS_TYPE info)
++#define NAN_SETTER(name)                                                       \
++    Nan::NAN_SETTER_RETURN_TYPE name(                                          \
++        v8::Local<v8::String> property                                         \
++      , v8::Local<v8::Value> value                                             \
++      , Nan::NAN_SETTER_ARGS_TYPE info)
++#define NAN_PROPERTY_GETTER(name)                                              \
++    Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name(                                 \
++        v8::Local<v8::String> property                                         \
++      , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info)
++#define NAN_PROPERTY_SETTER(name)                                              \
++    Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name(                                 \
++        v8::Local<v8::String> property                                         \
++      , v8::Local<v8::Value> value                                             \
++      , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info)
++#define NAN_PROPERTY_ENUMERATOR(name)                                          \
++    Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(                             \
++        Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info)
++#define NAN_PROPERTY_DELETER(name)                                             \
++    Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name(                                \
++        v8::Local<v8::String> property                                         \
++      , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info)
++#define NAN_PROPERTY_QUERY(name)                                               \
++    Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name(                                  \
++        v8::Local<v8::String> property                                         \
++      , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info)
++# define NAN_INDEX_GETTER(name)                                                \
++    Nan::NAN_INDEX_GETTER_RETURN_TYPE name(                                    \
++        uint32_t index                                                         \
++      , Nan::NAN_INDEX_GETTER_ARGS_TYPE info)
++#define NAN_INDEX_SETTER(name)                                                 \
++    Nan::NAN_INDEX_SETTER_RETURN_TYPE name(                                    \
++        uint32_t index                                                         \
++      , v8::Local<v8::Value> value                                             \
++      , Nan::NAN_INDEX_SETTER_ARGS_TYPE info)
++#define NAN_INDEX_ENUMERATOR(name)                                             \
++    Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE                                      \
++    name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info)
++#define NAN_INDEX_DELETER(name)                                                \
++    Nan::NAN_INDEX_DELETER_RETURN_TYPE name(                                   \
++        uint32_t index                                                         \
++      , Nan::NAN_INDEX_DELETER_ARGS_TYPE info)
++#define NAN_INDEX_QUERY(name)                                                  \
++    Nan::NAN_INDEX_QUERY_RETURN_TYPE name(                                     \
++        uint32_t index                                                         \
++      , Nan::NAN_INDEX_QUERY_ARGS_TYPE info)
++
++class Callback {
++ public:
++  Callback() {}
++
++  explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {}
++
++  ~Callback() {
++    handle_.Reset();
++  }
++
++  bool operator==(const Callback &other) const {
++    return handle_ == other.handle_;
++  }
++
++  bool operator!=(const Callback &other) const {
++    return !operator==(other);
++  }
++
++  inline
++  v8::Local<v8::Function> operator*() const { return GetFunction(); }
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
++      v8::Local<v8::Object> target
++    , int argc = 0
++    , v8::Local<v8::Value> argv[] = 0) const {
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource async("nan:Callback:operator()");
++    return Call_(isolate, target, argc, argv, &async)
++        .FromMaybe(v8::Local<v8::Value>());
++# else
++    return Call_(isolate, target, argc, argv);
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#else
++    return Call_(target, argc, argv);
++#endif  //  NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  }
++
++  NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
++      int argc = 0
++    , v8::Local<v8::Value> argv[] = 0) const {
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource async("nan:Callback:operator()");
++    return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
++                              argc, argv, &async)
++                            .FromMaybe(v8::Local<v8::Value>()));
++# else
++    return scope.Escape(
++        Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#else
++    v8::HandleScope scope;
++    return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
++#endif  //  NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  }
++
++  inline MaybeLocal<v8::Value> operator()(
++      AsyncResource* resource
++    , int argc = 0
++    , v8::Local<v8::Value> argv[] = 0) const {
++    return this->Call(argc, argv, resource);
++  }
++
++  inline MaybeLocal<v8::Value> operator()(
++      AsyncResource* resource
++    , v8::Local<v8::Object> target
++    , int argc = 0
++    , v8::Local<v8::Value> argv[] = 0) const {
++    return this->Call(target, argc, argv, resource);
++  }
++
++  // TODO(kkoopa): remove
++  inline void SetFunction(const v8::Local<v8::Function> &fn) {
++    Reset(fn);
++  }
++
++  inline void Reset(const v8::Local<v8::Function> &fn) {
++    handle_.Reset(fn);
++  }
++
++  inline void Reset() {
++    handle_.Reset();
++  }
++
++  inline v8::Local<v8::Function> GetFunction() const {
++    return New(handle_);
++  }
++
++  inline bool IsEmpty() const {
++    return handle_.IsEmpty();
++  }
++
++  // Deprecated: For async callbacks Use the versions that accept an
++  // AsyncResource. If this callback does not correspond to an async resource,
++  // that is, it is a synchronous function call on a non-empty JS stack, you
++  // should Nan::Call instead.
++  NAN_DEPRECATED inline v8::Local<v8::Value>
++  Call(v8::Local<v8::Object> target
++     , int argc
++     , v8::Local<v8::Value> argv[]) const {
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource async("nan:Callback:Call");
++    return Call_(isolate, target, argc, argv, &async)
++        .FromMaybe(v8::Local<v8::Value>());
++# else
++    return Call_(isolate, target, argc, argv);
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#else
++    return Call_(target, argc, argv);
++#endif
++  }
++
++  // Deprecated: For async callbacks Use the versions that accept an
++  // AsyncResource. If this callback does not correspond to an async resource,
++  // that is, it is a synchronous function call on a non-empty JS stack, you
++  // should Nan::Call instead.
++  NAN_DEPRECATED inline v8::Local<v8::Value>
++  Call(int argc, v8::Local<v8::Value> argv[]) const {
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    AsyncResource async("nan:Callback:Call");
++    return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
++                              argc, argv, &async)
++                            .FromMaybe(v8::Local<v8::Value>()));
++# else
++    return scope.Escape(
++        Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
++# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++#else
++    v8::HandleScope scope;
++    return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
++#endif
++  }
++
++  inline MaybeLocal<v8::Value>
++  Call(v8::Local<v8::Object> target
++     , int argc
++     , v8::Local<v8::Value> argv[]
++     , AsyncResource* resource) const {
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    v8::Isolate* isolate = v8::Isolate::GetCurrent();
++    return Call_(isolate, target, argc, argv, resource);
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    return Call_(isolate, target, argc, argv);
++#else
++    return Call_(target, argc, argv);
++#endif
++  }
++
++  inline MaybeLocal<v8::Value>
++  Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const {
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++    v8::Isolate* isolate = v8::Isolate::GetCurrent();
++    return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource);
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++    v8::Isolate *isolate = v8::Isolate::GetCurrent();
++    v8::EscapableHandleScope scope(isolate);
++    return scope.Escape(
++        Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
++#else
++    v8::HandleScope scope;
++    return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
++#endif
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback)
++  Persistent<v8::Function> handle_;
++
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++  MaybeLocal<v8::Value> Call_(v8::Isolate *isolate
++                            , v8::Local<v8::Object> target
++                            , int argc
++                            , v8::Local<v8::Value> argv[]
++                            , AsyncResource* resource) const {
++    EscapableHandleScope scope;
++    v8::Local<v8::Function> func = New(handle_);
++    auto maybe = resource->runInAsyncScope(target, func, argc, argv);
++    v8::Local<v8::Value> local;
++    if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>();
++    return scope.Escape(local);
++  }
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  v8::Local<v8::Value> Call_(v8::Isolate *isolate
++                           , v8::Local<v8::Object> target
++                           , int argc
++                           , v8::Local<v8::Value> argv[]) const {
++    EscapableHandleScope scope;
++
++    v8::Local<v8::Function> callback = New(handle_);
++# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++    return scope.Escape(New(node::MakeCallback(
++        isolate
++      , target
++      , callback
++      , argc
++      , argv
++    )));
++# else
++    return scope.Escape(node::MakeCallback(
++        isolate
++      , target
++      , callback
++      , argc
++      , argv
++    ));
++# endif
++  }
++#else
++  v8::Local<v8::Value> Call_(v8::Local<v8::Object> target
++                           , int argc
++                           , v8::Local<v8::Value> argv[]) const {
++    EscapableHandleScope scope;
++
++    v8::Local<v8::Function> callback = New(handle_);
++    return scope.Escape(New(node::MakeCallback(
++        target
++      , callback
++      , argc
++      , argv
++    )));
++  }
++#endif
++};
++
++inline MaybeLocal<v8::Value> Call(
++    const Nan::Callback& callback
++  , v8::Local<v8::Object> recv
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  return Call(*callback, recv, argc, argv);
++}
++
++inline MaybeLocal<v8::Value> Call(
++    const Nan::Callback& callback
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  v8::Isolate* isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(
++      Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv)
++          .FromMaybe(v8::Local<v8::Value>()));
++#else
++  EscapableHandleScope scope;
++  return scope.Escape(
++      Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv)
++          .FromMaybe(v8::Local<v8::Value>()));
++#endif
++}
++
++inline MaybeLocal<v8::Value> Call(
++    v8::Local<v8::String> symbol
++  , v8::Local<v8::Object> recv
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  EscapableHandleScope scope;
++  v8::Local<v8::Value> fn_v =
++      Get(recv, symbol).FromMaybe(v8::Local<v8::Value>());
++  if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>();
++  v8::Local<v8::Function> fn = fn_v.As<v8::Function>();
++  return scope.Escape(
++      Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline MaybeLocal<v8::Value> Call(
++    const char* method
++  , v8::Local<v8::Object> recv
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  EscapableHandleScope scope;
++  v8::Local<v8::String> method_string =
++      New<v8::String>(method).ToLocalChecked();
++  return scope.Escape(
++      Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
++}
++
++/* abstract */ class AsyncWorker {
++ public:
++  explicit AsyncWorker(Callback *callback_,
++                       const char* resource_name = "nan:AsyncWorker")
++      : callback(callback_), errmsg_(NULL) {
++    request.data = this;
++
++    HandleScope scope;
++    v8::Local<v8::Object> obj = New<v8::Object>();
++    persistentHandle.Reset(obj);
++    async_resource = new AsyncResource(resource_name, obj);
++  }
++
++  virtual ~AsyncWorker() {
++    HandleScope scope;
++
++    if (!persistentHandle.IsEmpty())
++      persistentHandle.Reset();
++    delete callback;
++    delete[] errmsg_;
++    delete async_resource;
++  }
++
++  virtual void WorkComplete() {
++    HandleScope scope;
++
++    if (errmsg_ == NULL)
++      HandleOKCallback();
++    else
++      HandleErrorCallback();
++    delete callback;
++    callback = NULL;
++  }
++
++  inline void SaveToPersistent(
++      const char *key, const v8::Local<v8::Value> &value) {
++    HandleScope scope;
++    Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust();
++  }
++
++  inline void SaveToPersistent(
++      const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) {
++    HandleScope scope;
++    Set(New(persistentHandle), key, value).FromJust();
++  }
++
++  inline void SaveToPersistent(
++      uint32_t index, const v8::Local<v8::Value> &value) {
++    HandleScope scope;
++    Set(New(persistentHandle), index, value).FromJust();
++  }
++
++  inline v8::Local<v8::Value> GetFromPersistent(const char *key) const {
++    EscapableHandleScope scope;
++    return scope.Escape(
++        Get(New(persistentHandle), New(key).ToLocalChecked())
++        .FromMaybe(v8::Local<v8::Value>()));
++  }
++
++  inline v8::Local<v8::Value>
++  GetFromPersistent(const v8::Local<v8::String> &key) const {
++    EscapableHandleScope scope;
++    return scope.Escape(
++        Get(New(persistentHandle), key)
++        .FromMaybe(v8::Local<v8::Value>()));
++  }
++
++  inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const {
++    EscapableHandleScope scope;
++    return scope.Escape(
++        Get(New(persistentHandle), index)
++        .FromMaybe(v8::Local<v8::Value>()));
++  }
++
++  virtual void Execute() = 0;
++
++  uv_work_t request;
++
++  virtual void Destroy() {
++      delete this;
++  }
++
++ protected:
++  Persistent<v8::Object> persistentHandle;
++  Callback *callback;
++  AsyncResource *async_resource;
++
++  virtual void HandleOKCallback() {
++    HandleScope scope;
++
++    callback->Call(0, NULL, async_resource);
++  }
++
++  virtual void HandleErrorCallback() {
++    HandleScope scope;
++
++    v8::Local<v8::Value> argv[] = {
++      v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked())
++    };
++    callback->Call(1, argv, async_resource);
++  }
++
++  void SetErrorMessage(const char *msg) {
++    delete[] errmsg_;
++
++    size_t size = strlen(msg) + 1;
++    errmsg_ = new char[size];
++    memcpy(errmsg_, msg, size);
++  }
++
++  const char* ErrorMessage() const {
++    return errmsg_;
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker)
++  char *errmsg_;
++};
++
++/* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker {
++ public:
++  explicit AsyncBareProgressWorkerBase(
++      Callback *callback_,
++      const char* resource_name = "nan:AsyncBareProgressWorkerBase")
++      : AsyncWorker(callback_, resource_name) {
++    uv_async_init(
++        GetCurrentEventLoop()
++      , &async
++      , AsyncProgress_
++    );
++    async.data = this;
++  }
++
++  virtual ~AsyncBareProgressWorkerBase() {
++  }
++
++  virtual void WorkProgress() = 0;
++
++  virtual void Destroy() {
++      uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_);
++  }
++
++ private:
++  inline static NAUV_WORK_CB(AsyncProgress_) {
++    AsyncBareProgressWorkerBase *worker =
++            static_cast<AsyncBareProgressWorkerBase*>(async->data);
++    worker->WorkProgress();
++  }
++
++  inline static void AsyncClose_(uv_handle_t* handle) {
++    AsyncBareProgressWorkerBase *worker =
++            static_cast<AsyncBareProgressWorkerBase*>(handle->data);
++    delete worker;
++  }
++
++ protected:
++  uv_async_t async;
++};
++
++template<class T>
++/* abstract */
++class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase {
++ public:
++  explicit AsyncBareProgressWorker(
++      Callback *callback_,
++      const char* resource_name = "nan:AsyncBareProgressWorker")
++      : AsyncBareProgressWorkerBase(callback_, resource_name) {
++    uv_mutex_init(&async_lock);
++  }
++
++  virtual ~AsyncBareProgressWorker() {
++    uv_mutex_destroy(&async_lock);
++  }
++
++  class ExecutionProgress {
++    friend class AsyncBareProgressWorker;
++   public:
++    void Signal() const {
++      uv_mutex_lock(&that_->async_lock);
++      uv_async_send(&that_->async);
++      uv_mutex_unlock(&that_->async_lock);
++    }
++
++    void Send(const T* data, size_t count) const {
++      that_->SendProgress_(data, count);
++    }
++
++   private:
++    explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {}
++    NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
++    AsyncBareProgressWorker* const that_;
++  };
++
++  virtual void Execute(const ExecutionProgress& progress) = 0;
++  virtual void HandleProgressCallback(const T *data, size_t size) = 0;
++
++ protected:
++  uv_mutex_t async_lock;
++
++ private:
++  void Execute() /*final override*/ {
++    ExecutionProgress progress(this);
++    Execute(progress);
++  }
++
++  virtual void SendProgress_(const T *data, size_t count) = 0;
++};
++
++template<class T>
++/* abstract */
++class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> {
++ public:
++  explicit AsyncProgressWorkerBase(
++      Callback *callback_,
++      const char* resource_name = "nan:AsyncProgressWorkerBase")
++      : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL),
++        asyncsize_(0) {
++  }
++
++  virtual ~AsyncProgressWorkerBase() {
++    delete[] asyncdata_;
++  }
++
++  void WorkProgress() {
++    uv_mutex_lock(&this->async_lock);
++    T *data = asyncdata_;
++    size_t size = asyncsize_;
++    asyncdata_ = NULL;
++    asyncsize_ = 0;
++    uv_mutex_unlock(&this->async_lock);
++
++    // Don't send progress events after we've already completed.
++    if (this->callback) {
++        this->HandleProgressCallback(data, size);
++    }
++    delete[] data;
++  }
++
++ private:
++  void SendProgress_(const T *data, size_t count) {
++    T *new_data = new T[count];
++    {
++      T *it = new_data;
++      std::copy(data, data + count, it);
++    }
++
++    uv_mutex_lock(&this->async_lock);
++    T *old_data = asyncdata_;
++    asyncdata_ = new_data;
++    asyncsize_ = count;
++    uv_async_send(&this->async);
++    uv_mutex_unlock(&this->async_lock);
++
++    delete[] old_data;
++  }
++
++  T *asyncdata_;
++  size_t asyncsize_;
++};
++
++// This ensures compatibility to the previous un-templated AsyncProgressWorker
++// class definition.
++typedef AsyncProgressWorkerBase<char> AsyncProgressWorker;
++
++template<class T>
++/* abstract */
++class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase {
++ public:
++  explicit AsyncBareProgressQueueWorker(
++      Callback *callback_,
++      const char* resource_name = "nan:AsyncBareProgressQueueWorker")
++      : AsyncBareProgressWorkerBase(callback_, resource_name) {
++  }
++
++  virtual ~AsyncBareProgressQueueWorker() {
++  }
++
++  class ExecutionProgress {
++    friend class AsyncBareProgressQueueWorker;
++   public:
++    void Send(const T* data, size_t count) const {
++      that_->SendProgress_(data, count);
++    }
++
++   private:
++    explicit ExecutionProgress(AsyncBareProgressQueueWorker *that)
++        : that_(that) {}
++    NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
++    AsyncBareProgressQueueWorker* const that_;
++  };
++
++  virtual void Execute(const ExecutionProgress& progress) = 0;
++  virtual void HandleProgressCallback(const T *data, size_t size) = 0;
++
++ private:
++  void Execute() /*final override*/ {
++    ExecutionProgress progress(this);
++    Execute(progress);
++  }
++
++  virtual void SendProgress_(const T *data, size_t count) = 0;
++};
++
++template<class T>
++/* abstract */
++class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> {
++ public:
++  explicit AsyncProgressQueueWorker(
++      Callback *callback_,
++      const char* resource_name = "nan:AsyncProgressQueueWorker")
++      : AsyncBareProgressQueueWorker<T>(callback_) {
++    uv_mutex_init(&async_lock);
++  }
++
++  virtual ~AsyncProgressQueueWorker() {
++    uv_mutex_lock(&async_lock);
++
++    while (!asyncdata_.empty()) {
++      std::pair<T*, size_t> &datapair = asyncdata_.front();
++      T *data = datapair.first;
++
++      asyncdata_.pop();
++
++      delete[] data;
++    }
++
++    uv_mutex_unlock(&async_lock);
++    uv_mutex_destroy(&async_lock);
++  }
++
++  void WorkComplete() {
++    WorkProgress();
++    AsyncWorker::WorkComplete();
++  }
++
++  void WorkProgress() {
++    uv_mutex_lock(&async_lock);
++
++    while (!asyncdata_.empty()) {
++      std::pair<T*, size_t> &datapair = asyncdata_.front();
++
++      T *data = datapair.first;
++      size_t size = datapair.second;
++
++      asyncdata_.pop();
++      uv_mutex_unlock(&async_lock);
++
++      // Don't send progress events after we've already completed.
++      if (this->callback) {
++          this->HandleProgressCallback(data, size);
++      }
++
++      delete[] data;
++
++      uv_mutex_lock(&async_lock);
++    }
++
++    uv_mutex_unlock(&async_lock);
++  }
++
++ private:
++  void SendProgress_(const T *data, size_t count) {
++    T *new_data = new T[count];
++    {
++      T *it = new_data;
++      std::copy(data, data + count, it);
++    }
++
++    uv_mutex_lock(&async_lock);
++    asyncdata_.push(std::pair<T*, size_t>(new_data, count));
++    uv_mutex_unlock(&async_lock);
++
++    uv_async_send(&this->async);
++  }
++
++  uv_mutex_t async_lock;
++  std::queue<std::pair<T*, size_t> > asyncdata_;
++};
++
++inline void AsyncExecute (uv_work_t* req) {
++  AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
++  worker->Execute();
++}
++
++inline void AsyncExecuteComplete (uv_work_t* req) {
++  AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
++  worker->WorkComplete();
++  worker->Destroy();
++}
++
++inline void AsyncQueueWorker (AsyncWorker* worker) {
++  uv_queue_work(
++      GetCurrentEventLoop()
++    , &worker->request
++    , AsyncExecute
++    , reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete)
++  );
++}
++
++namespace imp {
++
++inline
++ExternalOneByteStringResource const*
++GetExternalResource(v8::Local<v8::String> str) {
++#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
++    return str->GetExternalAsciiStringResource();
++#else
++    return str->GetExternalOneByteStringResource();
++#endif
++}
++
++inline
++bool
++IsExternal(v8::Local<v8::String> str) {
++#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
++    return str->IsExternalAscii();
++#else
++    return str->IsExternalOneByte();
++#endif
++}
++
++}  // end of namespace imp
++
++enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
++
++#if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION
++# include "nan_string_bytes.h"  // NOLINT(build/include)
++#endif
++
++inline v8::Local<v8::Value> Encode(
++    const void *buf, size_t len, enum Encoding encoding = BINARY) {
++#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION)
++  v8::Isolate* isolate = v8::Isolate::GetCurrent();
++  node::encoding node_enc = static_cast<node::encoding>(encoding);
++
++  if (encoding == UCS2) {
++    return node::Encode(
++        isolate
++      , reinterpret_cast<const uint16_t *>(buf)
++      , len / 2);
++  } else {
++    return node::Encode(
++        isolate
++      , reinterpret_cast<const char *>(buf)
++      , len
++      , node_enc);
++  }
++#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
++  return node::Encode(
++      v8::Isolate::GetCurrent()
++    , buf, len
++    , static_cast<node::encoding>(encoding));
++#else
++# if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
++  return node::Encode(buf, len, static_cast<node::encoding>(encoding));
++# else
++  return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding);
++# endif
++#endif
++}
++
++inline ssize_t DecodeBytes(
++    v8::Local<v8::Value> val, enum Encoding encoding = BINARY) {
++#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
++  return node::DecodeBytes(
++      v8::Isolate::GetCurrent()
++    , val
++    , static_cast<node::encoding>(encoding));
++#else
++# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
++  if (encoding == BUFFER) {
++    return node::DecodeBytes(val, node::BINARY);
++  }
++# endif
++  return node::DecodeBytes(val, static_cast<node::encoding>(encoding));
++#endif
++}
++
++inline ssize_t DecodeWrite(
++    char *buf
++  , size_t len
++  , v8::Local<v8::Value> val
++  , enum Encoding encoding = BINARY) {
++#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
++  return node::DecodeWrite(
++      v8::Isolate::GetCurrent()
++    , buf
++    , len
++    , val
++    , static_cast<node::encoding>(encoding));
++#else
++# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
++  if (encoding == BUFFER) {
++    return node::DecodeWrite(buf, len, val, node::BINARY);
++  }
++# endif
++  return node::DecodeWrite(
++      buf
++    , len
++    , val
++    , static_cast<node::encoding>(encoding));
++#endif
++}
++
++inline void SetPrototypeTemplate(
++    v8::Local<v8::FunctionTemplate> templ
++  , const char *name
++  , v8::Local<v8::Data> value
++) {
++  HandleScope scope;
++  SetTemplate(templ->PrototypeTemplate(), name, value);
++}
++
++inline void SetPrototypeTemplate(
++    v8::Local<v8::FunctionTemplate> templ
++  , v8::Local<v8::String> name
++  , v8::Local<v8::Data> value
++  , v8::PropertyAttribute attributes
++) {
++  HandleScope scope;
++  SetTemplate(templ->PrototypeTemplate(), name, value, attributes);
++}
++
++inline void SetInstanceTemplate(
++    v8::Local<v8::FunctionTemplate> templ
++  , const char *name
++  , v8::Local<v8::Data> value
++) {
++  HandleScope scope;
++  SetTemplate(templ->InstanceTemplate(), name, value);
++}
++
++inline void SetInstanceTemplate(
++    v8::Local<v8::FunctionTemplate> templ
++  , v8::Local<v8::String> name
++  , v8::Local<v8::Data> value
++  , v8::PropertyAttribute attributes
++) {
++  HandleScope scope;
++  SetTemplate(templ->InstanceTemplate(), name, value, attributes);
++}
++
++namespace imp {
++
++// Note(@agnat): Helper to distinguish different receiver types. The first
++// version deals with receivers derived from v8::Template. The second version
++// handles everything else. The final argument only serves as discriminator and
++// is unused.
++template <typename T>
++inline
++void
++SetMethodAux(T recv,
++             v8::Local<v8::String> name,
++             v8::Local<v8::FunctionTemplate> tpl,
++             v8::Template *) {
++  recv->Set(name, tpl);
++}
++
++template <typename T>
++inline
++void
++SetMethodAux(T recv,
++             v8::Local<v8::String> name,
++             v8::Local<v8::FunctionTemplate> tpl,
++             ...) {
++  Set(recv, name, GetFunction(tpl).ToLocalChecked());
++}
++
++}  // end of namespace imp
++
++template <typename T, template <typename> class HandleType>
++inline void SetMethod(
++    HandleType<T> recv
++  , const char *name
++  , FunctionCallback callback) {
++  HandleScope scope;
++  v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback);
++  v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
++  t->SetClassName(fn_name);
++  // Note(@agnat): Pass an empty T* as discriminator. See note on
++  // SetMethodAux(...) above
++  imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0));
++}
++
++inline void SetPrototypeMethod(
++    v8::Local<v8::FunctionTemplate> recv
++  , const char* name, FunctionCallback callback) {
++  HandleScope scope;
++  v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(
++      callback
++    , v8::Local<v8::Value>()
++    , New<v8::Signature>(recv));
++  v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
++  recv->PrototypeTemplate()->Set(fn_name, t);
++  t->SetClassName(fn_name);
++}
++
++//=== Accessors and Such =======================================================
++
++inline void SetAccessor(
++    v8::Local<v8::ObjectTemplate> tpl
++  , v8::Local<v8::String> name
++  , GetterCallback getter
++  , SetterCallback setter = 0
++  , v8::Local<v8::Value> data = v8::Local<v8::Value>()
++  , v8::AccessControl settings = v8::DEFAULT
++  , v8::PropertyAttribute attribute = v8::None
++  , imp::Sig signature = imp::Sig()) {
++  HandleScope scope;
++
++  imp::NativeGetter getter_ =
++      imp::GetterCallbackWrapper;
++  imp::NativeSetter setter_ =
++      setter ? imp::SetterCallbackWrapper : 0;
++
++  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
++  otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
++  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
++
++  obj->SetInternalField(
++      imp::kGetterIndex
++    , New<v8::External>(reinterpret_cast<void *>(getter)));
++
++  if (setter != 0) {
++    obj->SetInternalField(
++        imp::kSetterIndex
++      , New<v8::External>(reinterpret_cast<void *>(setter)));
++  }
++
++  if (!data.IsEmpty()) {
++    obj->SetInternalField(imp::kDataIndex, data);
++  }
++
++  tpl->SetAccessor(
++      name
++    , getter_
++    , setter_
++    , obj
++    , settings
++    , attribute
++    , signature);
++}
++
++inline bool SetAccessor(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> name
++  , GetterCallback getter
++  , SetterCallback setter = 0
++  , v8::Local<v8::Value> data = v8::Local<v8::Value>()
++  , v8::AccessControl settings = v8::DEFAULT
++  , v8::PropertyAttribute attribute = v8::None) {
++  HandleScope scope;
++
++  imp::NativeGetter getter_ =
++      imp::GetterCallbackWrapper;
++  imp::NativeSetter setter_ =
++      setter ? imp::SetterCallbackWrapper : 0;
++
++  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
++  otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
++  v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked();
++
++  dataobj->SetInternalField(
++      imp::kGetterIndex
++    , New<v8::External>(reinterpret_cast<void *>(getter)));
++
++  if (!data.IsEmpty()) {
++    dataobj->SetInternalField(imp::kDataIndex, data);
++  }
++
++  if (setter) {
++    dataobj->SetInternalField(
++        imp::kSetterIndex
++      , New<v8::External>(reinterpret_cast<void *>(setter)));
++  }
++
++#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
++  return obj->SetAccessor(
++      GetCurrentContext()
++    , name
++    , getter_
++    , setter_
++    , dataobj
++    , settings
++    , attribute).FromMaybe(false);
++#else
++  return obj->SetAccessor(
++      name
++    , getter_
++    , setter_
++    , dataobj
++    , settings
++    , attribute);
++#endif
++}
++
++inline void SetNamedPropertyHandler(
++    v8::Local<v8::ObjectTemplate> tpl
++  , PropertyGetterCallback getter
++  , PropertySetterCallback setter = 0
++  , PropertyQueryCallback query = 0
++  , PropertyDeleterCallback deleter = 0
++  , PropertyEnumeratorCallback enumerator = 0
++  , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
++  HandleScope scope;
++
++  imp::NativePropertyGetter getter_ =
++      imp::PropertyGetterCallbackWrapper;
++  imp::NativePropertySetter setter_ =
++      setter ? imp::PropertySetterCallbackWrapper : 0;
++  imp::NativePropertyQuery query_ =
++      query ? imp::PropertyQueryCallbackWrapper : 0;
++  imp::NativePropertyDeleter *deleter_ =
++      deleter ? imp::PropertyDeleterCallbackWrapper : 0;
++  imp::NativePropertyEnumerator enumerator_ =
++      enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0;
++
++  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
++  otpl->SetInternalFieldCount(imp::kPropertyFieldCount);
++  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
++  obj->SetInternalField(
++      imp::kPropertyGetterIndex
++    , New<v8::External>(reinterpret_cast<void *>(getter)));
++
++  if (setter) {
++    obj->SetInternalField(
++        imp::kPropertySetterIndex
++      , New<v8::External>(reinterpret_cast<void *>(setter)));
++  }
++
++  if (query) {
++    obj->SetInternalField(
++        imp::kPropertyQueryIndex
++      , New<v8::External>(reinterpret_cast<void *>(query)));
++  }
++
++  if (deleter) {
++    obj->SetInternalField(
++        imp::kPropertyDeleterIndex
++      , New<v8::External>(reinterpret_cast<void *>(deleter)));
++  }
++
++  if (enumerator) {
++    obj->SetInternalField(
++        imp::kPropertyEnumeratorIndex
++      , New<v8::External>(reinterpret_cast<void *>(enumerator)));
++  }
++
++  if (!data.IsEmpty()) {
++    obj->SetInternalField(imp::kDataIndex, data);
++  }
++
++#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++  tpl->SetHandler(v8::NamedPropertyHandlerConfiguration(
++      getter_, setter_, query_, deleter_, enumerator_, obj));
++#else
++  tpl->SetNamedPropertyHandler(
++      getter_
++    , setter_
++    , query_
++    , deleter_
++    , enumerator_
++    , obj);
++#endif
++}
++
++inline void SetIndexedPropertyHandler(
++    v8::Local<v8::ObjectTemplate> tpl
++  , IndexGetterCallback getter
++  , IndexSetterCallback setter = 0
++  , IndexQueryCallback query = 0
++  , IndexDeleterCallback deleter = 0
++  , IndexEnumeratorCallback enumerator = 0
++  , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
++  HandleScope scope;
++
++  imp::NativeIndexGetter getter_ =
++      imp::IndexGetterCallbackWrapper;
++  imp::NativeIndexSetter setter_ =
++      setter ? imp::IndexSetterCallbackWrapper : 0;
++  imp::NativeIndexQuery query_ =
++      query ? imp::IndexQueryCallbackWrapper : 0;
++  imp::NativeIndexDeleter deleter_ =
++      deleter ? imp::IndexDeleterCallbackWrapper : 0;
++  imp::NativeIndexEnumerator enumerator_ =
++      enumerator ? imp::IndexEnumeratorCallbackWrapper : 0;
++
++  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
++  otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount);
++  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
++  obj->SetInternalField(
++      imp::kIndexPropertyGetterIndex
++    , New<v8::External>(reinterpret_cast<void *>(getter)));
++
++  if (setter) {
++    obj->SetInternalField(
++        imp::kIndexPropertySetterIndex
++      , New<v8::External>(reinterpret_cast<void *>(setter)));
++  }
++
++  if (query) {
++    obj->SetInternalField(
++        imp::kIndexPropertyQueryIndex
++      , New<v8::External>(reinterpret_cast<void *>(query)));
++  }
++
++  if (deleter) {
++    obj->SetInternalField(
++        imp::kIndexPropertyDeleterIndex
++      , New<v8::External>(reinterpret_cast<void *>(deleter)));
++  }
++
++  if (enumerator) {
++    obj->SetInternalField(
++        imp::kIndexPropertyEnumeratorIndex
++      , New<v8::External>(reinterpret_cast<void *>(enumerator)));
++  }
++
++  if (!data.IsEmpty()) {
++    obj->SetInternalField(imp::kDataIndex, data);
++  }
++
++#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++  tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration(
++      getter_, setter_, query_, deleter_, enumerator_, obj));
++#else
++  tpl->SetIndexedPropertyHandler(
++      getter_
++    , setter_
++    , query_
++    , deleter_
++    , enumerator_
++    , obj);
++#endif
++}
++
++inline void SetCallHandler(
++    v8::Local<v8::FunctionTemplate> tpl
++  , FunctionCallback callback
++  , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
++  HandleScope scope;
++
++  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
++  otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
++  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
++
++  obj->SetInternalField(
++      imp::kFunctionIndex
++    , New<v8::External>(reinterpret_cast<void *>(callback)));
++
++  if (!data.IsEmpty()) {
++    obj->SetInternalField(imp::kDataIndex, data);
++  }
++
++  tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj);
++}
++
++
++inline void SetCallAsFunctionHandler(
++    v8::Local<v8::ObjectTemplate> tpl,
++    FunctionCallback callback,
++    v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
++  HandleScope scope;
++
++  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
++  otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
++  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
++
++  obj->SetInternalField(
++      imp::kFunctionIndex
++    , New<v8::External>(reinterpret_cast<void *>(callback)));
++
++  if (!data.IsEmpty()) {
++    obj->SetInternalField(imp::kDataIndex, data);
++  }
++
++  tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj);
++}
++
++//=== Weak Persistent Handling =================================================
++
++#include "nan_weak.h"  // NOLINT(build/include)
++
++//=== ObjectWrap ===============================================================
++
++#include "nan_object_wrap.h"  // NOLINT(build/include)
++
++//=== HiddenValue/Private ======================================================
++
++#include "nan_private.h"  // NOLINT(build/include)
++
++//=== Export ==================================================================
++
++inline
++void
++Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name,
++    FunctionCallback f) {
++  HandleScope scope;
++
++  Set(target, New<v8::String>(name).ToLocalChecked(),
++      GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked());
++}
++
++//=== Tap Reverse Binding =====================================================
++
++struct Tap {
++  explicit Tap(v8::Local<v8::Value> t) : t_() {
++    HandleScope scope;
++
++    t_.Reset(To<v8::Object>(t).ToLocalChecked());
++  }
++
++  ~Tap() { t_.Reset(); }  // not sure if neccessary
++
++  inline void plan(int i) {
++    HandleScope scope;
++    v8::Local<v8::Value> arg = New(i);
++    Call("plan", New(t_), 1, &arg);
++  }
++
++  inline void ok(bool isOk, const char *msg = NULL) {
++    HandleScope scope;
++    v8::Local<v8::Value> args[2];
++    args[0] = New(isOk);
++    if (msg) args[1] = New(msg).ToLocalChecked();
++    Call("ok", New(t_), msg ? 2 : 1, args);
++  }
++
++  inline void pass(const char * msg = NULL) {
++    HandleScope scope;
++    v8::Local<v8::Value> hmsg;
++    if (msg) hmsg = New(msg).ToLocalChecked();
++    Call("pass", New(t_), msg ? 1 : 0, &hmsg);
++  }
++
++  inline void end() {
++    HandleScope scope;
++    Call("end", New(t_), 0, NULL);
++  }
++
++ private:
++  Persistent<v8::Object> t_;
++};
++
++#define NAN_STRINGIZE2(x) #x
++#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x)
++#define NAN_TEST_EXPRESSION(expression) \
++  ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression
++
++#define NAN_EXPORT(target, function) Export(target, #function, function)
++
++#undef TYPE_CHECK
++
++//=== Generic Maybefication ===================================================
++
++namespace imp {
++
++template <typename T> struct Maybefier;
++
++template <typename T> struct Maybefier<v8::Local<T> > {
++  inline static MaybeLocal<T> convert(v8::Local<T> v) {
++    return v;
++  }
++};
++
++template <typename T> struct Maybefier<MaybeLocal<T> > {
++  inline static MaybeLocal<T> convert(MaybeLocal<T> v) {
++    return v;
++  }
++};
++
++}  // end of namespace imp
++
++template <typename T, template <typename> class MaybeMaybe>
++inline MaybeLocal<T>
++MakeMaybe(MaybeMaybe<T> v) {
++  return imp::Maybefier<MaybeMaybe<T> >::convert(v);
++}
++
++//=== TypedArrayContents =======================================================
++
++#include "nan_typedarray_contents.h"  // NOLINT(build/include)
++
++//=== JSON =====================================================================
++
++#include "nan_json.h"  // NOLINT(build/include)
++
++}  // end of namespace Nan
++
++#endif  // NAN_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..53ede846ac9a865a737218dabbbd48305d3d6b63
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,88 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_CALLBACKS_H_
++#define NAN_CALLBACKS_H_
++
++template<typename T> class FunctionCallbackInfo;
++template<typename T> class PropertyCallbackInfo;
++template<typename T> class Global;
++
++typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
++typedef void(*GetterCallback)
++    (v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&);
++typedef void(*SetterCallback)(
++    v8::Local<v8::String>,
++    v8::Local<v8::Value>,
++    const PropertyCallbackInfo<void>&);
++typedef void(*PropertyGetterCallback)(
++    v8::Local<v8::String>,
++    const PropertyCallbackInfo<v8::Value>&);
++typedef void(*PropertySetterCallback)(
++    v8::Local<v8::String>,
++    v8::Local<v8::Value>,
++    const PropertyCallbackInfo<v8::Value>&);
++typedef void(*PropertyEnumeratorCallback)
++    (const PropertyCallbackInfo<v8::Array>&);
++typedef void(*PropertyDeleterCallback)(
++    v8::Local<v8::String>,
++    const PropertyCallbackInfo<v8::Boolean>&);
++typedef void(*PropertyQueryCallback)(
++    v8::Local<v8::String>,
++    const PropertyCallbackInfo<v8::Integer>&);
++typedef void(*IndexGetterCallback)(
++    uint32_t,
++    const PropertyCallbackInfo<v8::Value>&);
++typedef void(*IndexSetterCallback)(
++    uint32_t,
++    v8::Local<v8::Value>,
++    const PropertyCallbackInfo<v8::Value>&);
++typedef void(*IndexEnumeratorCallback)
++    (const PropertyCallbackInfo<v8::Array>&);
++typedef void(*IndexDeleterCallback)(
++    uint32_t,
++    const PropertyCallbackInfo<v8::Boolean>&);
++typedef void(*IndexQueryCallback)(
++    uint32_t,
++    const PropertyCallbackInfo<v8::Integer>&);
++
++namespace imp {
++typedef v8::Local<v8::AccessorSignature> Sig;
++
++static const int kDataIndex =                    0;
++
++static const int kFunctionIndex =                1;
++static const int kFunctionFieldCount =           2;
++
++static const int kGetterIndex =                  1;
++static const int kSetterIndex =                  2;
++static const int kAccessorFieldCount =           3;
++
++static const int kPropertyGetterIndex =          1;
++static const int kPropertySetterIndex =          2;
++static const int kPropertyEnumeratorIndex =      3;
++static const int kPropertyDeleterIndex =         4;
++static const int kPropertyQueryIndex =           5;
++static const int kPropertyFieldCount =           6;
++
++static const int kIndexPropertyGetterIndex =     1;
++static const int kIndexPropertySetterIndex =     2;
++static const int kIndexPropertyEnumeratorIndex = 3;
++static const int kIndexPropertyDeleterIndex =    4;
++static const int kIndexPropertyQueryIndex =      5;
++static const int kIndexPropertyFieldCount =      6;
++
++}  // end of namespace imp
++
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++# include "nan_callbacks_12_inl.h"  // NOLINT(build/include)
++#else
++# include "nan_callbacks_pre_12_inl.h"  // NOLINT(build/include)
++#endif
++
++#endif  // NAN_CALLBACKS_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c27b18d80d1299ff2142606d333804696bc17f93
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,514 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_CALLBACKS_12_INL_H_
++#define NAN_CALLBACKS_12_INL_H_
++
++template<typename T>
++class ReturnValue {
++  v8::ReturnValue<T> value_;
++
++ public:
++  template <class S>
++  explicit inline ReturnValue(const v8::ReturnValue<S> &value) :
++      value_(value) {}
++  template <class S>
++  explicit inline ReturnValue(const ReturnValue<S>& that)
++      : value_(that.value_) {
++    TYPE_CHECK(T, S);
++  }
++
++  // Handle setters
++  template <typename S> inline void Set(const v8::Local<S> &handle) {
++    TYPE_CHECK(T, S);
++    value_.Set(handle);
++  }
++
++  template <typename S> inline void Set(const Global<S> &handle) {
++    TYPE_CHECK(T, S);
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) &&                       \
++  (V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 &&                           \
++  defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8))))
++    value_.Set(handle);
++#else
++    value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle));
++    const_cast<Global<S> &>(handle).Reset();
++#endif
++  }
++
++  // Fast primitive setters
++  inline void Set(bool value) {
++    TYPE_CHECK(T, v8::Boolean);
++    value_.Set(value);
++  }
++
++  inline void Set(double i) {
++    TYPE_CHECK(T, v8::Number);
++    value_.Set(i);
++  }
++
++  inline void Set(int32_t i) {
++    TYPE_CHECK(T, v8::Integer);
++    value_.Set(i);
++  }
++
++  inline void Set(uint32_t i) {
++    TYPE_CHECK(T, v8::Integer);
++    value_.Set(i);
++  }
++
++  // Fast JS primitive setters
++  inline void SetNull() {
++    TYPE_CHECK(T, v8::Primitive);
++    value_.SetNull();
++  }
++
++  inline void SetUndefined() {
++    TYPE_CHECK(T, v8::Primitive);
++    value_.SetUndefined();
++  }
++
++  inline void SetEmptyString() {
++    TYPE_CHECK(T, v8::String);
++    value_.SetEmptyString();
++  }
++
++  // Convenience getter for isolate
++  inline v8::Isolate *GetIsolate() const {
++    return value_.GetIsolate();
++  }
++
++  // Pointer setter: Uncompilable to prevent inadvertent misuse.
++  template<typename S>
++  inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
++};
++
++template<typename T>
++class FunctionCallbackInfo {
++  const v8::FunctionCallbackInfo<T> &info_;
++  const v8::Local<v8::Value> data_;
++
++ public:
++  explicit inline FunctionCallbackInfo(
++      const v8::FunctionCallbackInfo<T> &info
++    , v8::Local<v8::Value> data) :
++          info_(info)
++        , data_(data) {}
++
++  inline ReturnValue<T> GetReturnValue() const {
++    return ReturnValue<T>(info_.GetReturnValue());
++  }
++
++#if NODE_MAJOR_VERSION < 10
++  inline v8::Local<v8::Function> Callee() const { return info_.Callee(); }
++#endif
++  inline v8::Local<v8::Value> Data() const { return data_; }
++  inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
++  inline bool IsConstructCall() const { return info_.IsConstructCall(); }
++  inline int Length() const { return info_.Length(); }
++  inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; }
++  inline v8::Local<v8::Object> This() const { return info_.This(); }
++  inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); }
++
++
++ protected:
++  static const int kHolderIndex = 0;
++  static const int kIsolateIndex = 1;
++  static const int kReturnValueDefaultValueIndex = 2;
++  static const int kReturnValueIndex = 3;
++  static const int kDataIndex = 4;
++  static const int kCalleeIndex = 5;
++  static const int kContextSaveIndex = 6;
++  static const int kArgsLength = 7;
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
++};
++
++template<typename T>
++class PropertyCallbackInfo {
++  const v8::PropertyCallbackInfo<T> &info_;
++  const v8::Local<v8::Value> data_;
++
++ public:
++  explicit inline PropertyCallbackInfo(
++      const v8::PropertyCallbackInfo<T> &info
++    , const v8::Local<v8::Value> data) :
++          info_(info)
++        , data_(data) {}
++
++  inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
++  inline v8::Local<v8::Value> Data() const { return data_; }
++  inline v8::Local<v8::Object> This() const { return info_.This(); }
++  inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
++  inline ReturnValue<T> GetReturnValue() const {
++    return ReturnValue<T>(info_.GetReturnValue());
++  }
++
++ protected:
++  static const int kHolderIndex = 0;
++  static const int kIsolateIndex = 1;
++  static const int kReturnValueDefaultValueIndex = 2;
++  static const int kReturnValueIndex = 3;
++  static const int kDataIndex = 4;
++  static const int kThisIndex = 5;
++  static const int kArgsLength = 6;
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo)
++};
++
++namespace imp {
++static
++void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  FunctionCallback callback = reinterpret_cast<FunctionCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
++  FunctionCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  callback(cbinfo);
++}
++
++typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &);
++
++#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++static
++void GetterCallbackWrapper(
++    v8::Local<v8::Name> property
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  GetterCallback callback = reinterpret_cast<GetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
++  callback(property.As<v8::String>(), cbinfo);
++}
++
++typedef void (*NativeGetter)
++    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void SetterCallbackWrapper(
++    v8::Local<v8::Name> property
++  , v8::Local<v8::Value> value
++  , const v8::PropertyCallbackInfo<void> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<void>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  SetterCallback callback = reinterpret_cast<SetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
++  callback(property.As<v8::String>(), value, cbinfo);
++}
++
++typedef void (*NativeSetter)(
++    v8::Local<v8::Name>
++  , v8::Local<v8::Value>
++  , const v8::PropertyCallbackInfo<void> &);
++#else
++static
++void GetterCallbackWrapper(
++    v8::Local<v8::String> property
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  GetterCallback callback = reinterpret_cast<GetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
++  callback(property, cbinfo);
++}
++
++typedef void (*NativeGetter)
++    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void SetterCallbackWrapper(
++    v8::Local<v8::String> property
++  , v8::Local<v8::Value> value
++  , const v8::PropertyCallbackInfo<void> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<void>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  SetterCallback callback = reinterpret_cast<SetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
++  callback(property, value, cbinfo);
++}
++
++typedef void (*NativeSetter)(
++    v8::Local<v8::String>
++  , v8::Local<v8::Value>
++  , const v8::PropertyCallbackInfo<void> &);
++#endif
++
++#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++static
++void PropertyGetterCallbackWrapper(
++    v8::Local<v8::Name> property
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyGetterIndex)
++              .As<v8::External>()->Value()));
++  callback(property.As<v8::String>(), cbinfo);
++}
++
++typedef void (*NativePropertyGetter)
++    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void PropertySetterCallbackWrapper(
++    v8::Local<v8::Name> property
++  , v8::Local<v8::Value> value
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertySetterIndex)
++              .As<v8::External>()->Value()));
++  callback(property.As<v8::String>(), value, cbinfo);
++}
++
++typedef void (*NativePropertySetter)(
++    v8::Local<v8::Name>
++  , v8::Local<v8::Value>
++  , const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void PropertyEnumeratorCallbackWrapper(
++    const v8::PropertyCallbackInfo<v8::Array> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Array>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyEnumeratorCallback callback =
++      reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyEnumeratorIndex)
++              .As<v8::External>()->Value()));
++  callback(cbinfo);
++}
++
++typedef void (*NativePropertyEnumerator)
++    (const v8::PropertyCallbackInfo<v8::Array> &);
++
++static
++void PropertyDeleterCallbackWrapper(
++    v8::Local<v8::Name> property
++  , const v8::PropertyCallbackInfo<v8::Boolean> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Boolean>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyDeleterIndex)
++              .As<v8::External>()->Value()));
++  callback(property.As<v8::String>(), cbinfo);
++}
++
++typedef void (NativePropertyDeleter)
++    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &);
++
++static
++void PropertyQueryCallbackWrapper(
++    v8::Local<v8::Name> property
++  , const v8::PropertyCallbackInfo<v8::Integer> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Integer>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyQueryIndex)
++              .As<v8::External>()->Value()));
++  callback(property.As<v8::String>(), cbinfo);
++}
++
++typedef void (*NativePropertyQuery)
++    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &);
++#else
++static
++void PropertyGetterCallbackWrapper(
++    v8::Local<v8::String> property
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyGetterIndex)
++              .As<v8::External>()->Value()));
++  callback(property, cbinfo);
++}
++
++typedef void (*NativePropertyGetter)
++    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void PropertySetterCallbackWrapper(
++    v8::Local<v8::String> property
++  , v8::Local<v8::Value> value
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertySetterIndex)
++              .As<v8::External>()->Value()));
++  callback(property, value, cbinfo);
++}
++
++typedef void (*NativePropertySetter)(
++    v8::Local<v8::String>
++  , v8::Local<v8::Value>
++  , const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void PropertyEnumeratorCallbackWrapper(
++    const v8::PropertyCallbackInfo<v8::Array> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Array>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyEnumeratorCallback callback =
++      reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyEnumeratorIndex)
++              .As<v8::External>()->Value()));
++  callback(cbinfo);
++}
++
++typedef void (*NativePropertyEnumerator)
++    (const v8::PropertyCallbackInfo<v8::Array> &);
++
++static
++void PropertyDeleterCallbackWrapper(
++    v8::Local<v8::String> property
++  , const v8::PropertyCallbackInfo<v8::Boolean> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Boolean>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyDeleterIndex)
++              .As<v8::External>()->Value()));
++  callback(property, cbinfo);
++}
++
++typedef void (NativePropertyDeleter)
++    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &);
++
++static
++void PropertyQueryCallbackWrapper(
++    v8::Local<v8::String> property
++  , const v8::PropertyCallbackInfo<v8::Integer> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Integer>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyQueryIndex)
++              .As<v8::External>()->Value()));
++  callback(property, cbinfo);
++}
++
++typedef void (*NativePropertyQuery)
++    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &);
++#endif
++
++static
++void IndexGetterCallbackWrapper(
++    uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyGetterIndex)
++              .As<v8::External>()->Value()));
++  callback(index, cbinfo);
++}
++
++typedef void (*NativeIndexGetter)
++    (uint32_t, const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void IndexSetterCallbackWrapper(
++    uint32_t index
++  , v8::Local<v8::Value> value
++  , const v8::PropertyCallbackInfo<v8::Value> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertySetterIndex)
++              .As<v8::External>()->Value()));
++  callback(index, value, cbinfo);
++}
++
++typedef void (*NativeIndexSetter)(
++    uint32_t
++  , v8::Local<v8::Value>
++  , const v8::PropertyCallbackInfo<v8::Value> &);
++
++static
++void IndexEnumeratorCallbackWrapper(
++    const v8::PropertyCallbackInfo<v8::Array> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Array>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(
++              kIndexPropertyEnumeratorIndex).As<v8::External>()->Value()));
++  callback(cbinfo);
++}
++
++typedef void (*NativeIndexEnumerator)
++    (const v8::PropertyCallbackInfo<v8::Array> &);
++
++static
++void IndexDeleterCallbackWrapper(
++    uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Boolean>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyDeleterIndex)
++              .As<v8::External>()->Value()));
++  callback(index, cbinfo);
++}
++
++typedef void (*NativeIndexDeleter)
++    (uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &);
++
++static
++void IndexQueryCallbackWrapper(
++    uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Integer>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyQueryIndex)
++              .As<v8::External>()->Value()));
++  callback(index, cbinfo);
++}
++
++typedef void (*NativeIndexQuery)
++    (uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &);
++}  // end of namespace imp
++
++#endif  // NAN_CALLBACKS_12_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c9ba4993205ec4feed387870b8f33f05e0789f1a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,520 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_CALLBACKS_PRE_12_INL_H_
++#define NAN_CALLBACKS_PRE_12_INL_H_
++
++namespace imp {
++template<typename T> class ReturnValueImp;
++}  // end of namespace imp
++
++template<typename T>
++class ReturnValue {
++  v8::Isolate *isolate_;
++  v8::Persistent<T> *value_;
++  friend class imp::ReturnValueImp<T>;
++
++ public:
++  template <class S>
++  explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) :
++      isolate_(isolate), value_(p) {}
++  template <class S>
++  explicit inline ReturnValue(const ReturnValue<S>& that)
++      : isolate_(that.isolate_), value_(that.value_) {
++    TYPE_CHECK(T, S);
++  }
++
++  // Handle setters
++  template <typename S> inline void Set(const v8::Local<S> &handle) {
++    TYPE_CHECK(T, S);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(handle);
++  }
++
++  template <typename S> inline void Set(const Global<S> &handle) {
++    TYPE_CHECK(T, S);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(handle.persistent);
++    const_cast<Global<S> &>(handle).Reset();
++  }
++
++  // Fast primitive setters
++  inline void Set(bool value) {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::Boolean);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::Boolean::New(value));
++  }
++
++  inline void Set(double i) {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::Number);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::Number::New(i));
++  }
++
++  inline void Set(int32_t i) {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::Integer);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::Int32::New(i));
++  }
++
++  inline void Set(uint32_t i) {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::Integer);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::Uint32::NewFromUnsigned(i));
++  }
++
++  // Fast JS primitive setters
++  inline void SetNull() {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::Primitive);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::Null());
++  }
++
++  inline void SetUndefined() {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::Primitive);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::Undefined());
++  }
++
++  inline void SetEmptyString() {
++    v8::HandleScope scope;
++
++    TYPE_CHECK(T, v8::String);
++    value_->Dispose();
++    *value_ = v8::Persistent<T>::New(v8::String::Empty());
++  }
++
++  // Convenience getter for isolate
++  inline v8::Isolate *GetIsolate() const {
++    return isolate_;
++  }
++
++  // Pointer setter: Uncompilable to prevent inadvertent misuse.
++  template<typename S>
++  inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
++};
++
++template<typename T>
++class FunctionCallbackInfo {
++  const v8::Arguments &args_;
++  v8::Local<v8::Value> data_;
++  ReturnValue<T> return_value_;
++  v8::Persistent<T> retval_;
++
++ public:
++  explicit inline FunctionCallbackInfo(
++      const v8::Arguments &args
++    , v8::Local<v8::Value> data) :
++          args_(args)
++        , data_(data)
++        , return_value_(args.GetIsolate(), &retval_)
++        , retval_(v8::Persistent<T>::New(v8::Undefined())) {}
++
++  inline ~FunctionCallbackInfo() {
++    retval_.Dispose();
++    retval_.Clear();
++  }
++
++  inline ReturnValue<T> GetReturnValue() const {
++    return ReturnValue<T>(return_value_);
++  }
++
++  inline v8::Local<v8::Function> Callee() const { return args_.Callee(); }
++  inline v8::Local<v8::Value> Data() const { return data_; }
++  inline v8::Local<v8::Object> Holder() const { return args_.Holder(); }
++  inline bool IsConstructCall() const { return args_.IsConstructCall(); }
++  inline int Length() const { return args_.Length(); }
++  inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; }
++  inline v8::Local<v8::Object> This() const { return args_.This(); }
++  inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); }
++
++
++ protected:
++  static const int kHolderIndex = 0;
++  static const int kIsolateIndex = 1;
++  static const int kReturnValueDefaultValueIndex = 2;
++  static const int kReturnValueIndex = 3;
++  static const int kDataIndex = 4;
++  static const int kCalleeIndex = 5;
++  static const int kContextSaveIndex = 6;
++  static const int kArgsLength = 7;
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
++};
++
++template<typename T>
++class PropertyCallbackInfoBase {
++  const v8::AccessorInfo &info_;
++  const v8::Local<v8::Value> data_;
++
++ public:
++  explicit inline PropertyCallbackInfoBase(
++      const v8::AccessorInfo &info
++    , const v8::Local<v8::Value> data) :
++          info_(info)
++        , data_(data) {}
++
++  inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
++  inline v8::Local<v8::Value> Data() const { return data_; }
++  inline v8::Local<v8::Object> This() const { return info_.This(); }
++  inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
++
++ protected:
++  static const int kHolderIndex = 0;
++  static const int kIsolateIndex = 1;
++  static const int kReturnValueDefaultValueIndex = 2;
++  static const int kReturnValueIndex = 3;
++  static const int kDataIndex = 4;
++  static const int kThisIndex = 5;
++  static const int kArgsLength = 6;
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase)
++};
++
++template<typename T>
++class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
++  ReturnValue<T> return_value_;
++  v8::Persistent<T> retval_;
++
++ public:
++  explicit inline PropertyCallbackInfo(
++      const v8::AccessorInfo &info
++    , const v8::Local<v8::Value> data) :
++          PropertyCallbackInfoBase<T>(info, data)
++        , return_value_(info.GetIsolate(), &retval_)
++        , retval_(v8::Persistent<T>::New(v8::Undefined())) {}
++
++  inline ~PropertyCallbackInfo() {
++    retval_.Dispose();
++    retval_.Clear();
++  }
++
++  inline ReturnValue<T> GetReturnValue() const { return return_value_; }
++};
++
++template<>
++class PropertyCallbackInfo<v8::Array> :
++    public PropertyCallbackInfoBase<v8::Array> {
++  ReturnValue<v8::Array> return_value_;
++  v8::Persistent<v8::Array> retval_;
++
++ public:
++  explicit inline PropertyCallbackInfo(
++      const v8::AccessorInfo &info
++    , const v8::Local<v8::Value> data) :
++          PropertyCallbackInfoBase<v8::Array>(info, data)
++        , return_value_(info.GetIsolate(), &retval_)
++        , retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {}
++
++  inline ~PropertyCallbackInfo() {
++    retval_.Dispose();
++    retval_.Clear();
++  }
++
++  inline ReturnValue<v8::Array> GetReturnValue() const {
++    return return_value_;
++  }
++};
++
++template<>
++class PropertyCallbackInfo<v8::Boolean> :
++    public PropertyCallbackInfoBase<v8::Boolean> {
++  ReturnValue<v8::Boolean> return_value_;
++  v8::Persistent<v8::Boolean> retval_;
++
++ public:
++  explicit inline PropertyCallbackInfo(
++      const v8::AccessorInfo &info
++    , const v8::Local<v8::Value> data) :
++          PropertyCallbackInfoBase<v8::Boolean>(info, data)
++        , return_value_(info.GetIsolate(), &retval_)
++        , retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {}
++
++  inline ~PropertyCallbackInfo() {
++    retval_.Dispose();
++    retval_.Clear();
++  }
++
++  inline ReturnValue<v8::Boolean> GetReturnValue() const {
++    return return_value_;
++  }
++};
++
++template<>
++class PropertyCallbackInfo<v8::Integer> :
++    public PropertyCallbackInfoBase<v8::Integer> {
++  ReturnValue<v8::Integer> return_value_;
++  v8::Persistent<v8::Integer> retval_;
++
++ public:
++  explicit inline PropertyCallbackInfo(
++      const v8::AccessorInfo &info
++    , const v8::Local<v8::Value> data) :
++          PropertyCallbackInfoBase<v8::Integer>(info, data)
++        , return_value_(info.GetIsolate(), &retval_)
++        , retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {}
++
++  inline ~PropertyCallbackInfo() {
++    retval_.Dispose();
++    retval_.Clear();
++  }
++
++  inline ReturnValue<v8::Integer> GetReturnValue() const {
++    return return_value_;
++  }
++};
++
++namespace imp {
++template<typename T>
++class ReturnValueImp : public ReturnValue<T> {
++ public:
++  explicit ReturnValueImp(ReturnValue<T> that) :
++      ReturnValue<T>(that) {}
++  inline v8::Handle<T> Value() {
++      return *ReturnValue<T>::value_;
++  }
++};
++
++static
++v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) {
++  v8::Local<v8::Object> obj = args.Data().As<v8::Object>();
++  FunctionCallback callback = reinterpret_cast<FunctionCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
++  FunctionCallbackInfo<v8::Value>
++      cbinfo(args, obj->GetInternalField(kDataIndex));
++  callback(cbinfo);
++  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &);
++
++static
++v8::Handle<v8::Value> GetterCallbackWrapper(
++    v8::Local<v8::String> property, const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  GetterCallback callback = reinterpret_cast<GetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
++  callback(property, cbinfo);
++  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Value> (*NativeGetter)
++    (v8::Local<v8::String>, const v8::AccessorInfo &);
++
++static
++void SetterCallbackWrapper(
++    v8::Local<v8::String> property
++  , v8::Local<v8::Value> value
++  , const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<void>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  SetterCallback callback = reinterpret_cast<SetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
++  callback(property, value, cbinfo);
++}
++
++typedef void (*NativeSetter)
++    (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Value> PropertyGetterCallbackWrapper(
++    v8::Local<v8::String> property, const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyGetterIndex)
++              .As<v8::External>()->Value()));
++  callback(property, cbinfo);
++  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Value> (*NativePropertyGetter)
++    (v8::Local<v8::String>, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Value> PropertySetterCallbackWrapper(
++    v8::Local<v8::String> property
++  , v8::Local<v8::Value> value
++  , const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertySetterIndex)
++              .As<v8::External>()->Value()));
++  callback(property, value, cbinfo);
++  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Value> (*NativePropertySetter)
++    (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper(
++    const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Array>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyEnumeratorCallback callback =
++      reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyEnumeratorIndex)
++              .As<v8::External>()->Value()));
++  callback(cbinfo);
++  return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Array> (*NativePropertyEnumerator)
++    (const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper(
++    v8::Local<v8::String> property
++  , const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Boolean>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyDeleterIndex)
++              .As<v8::External>()->Value()));
++  callback(property, cbinfo);
++  return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Boolean> (NativePropertyDeleter)
++    (v8::Local<v8::String>, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Integer> PropertyQueryCallbackWrapper(
++    v8::Local<v8::String> property, const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Integer>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kPropertyQueryIndex)
++              .As<v8::External>()->Value()));
++  callback(property, cbinfo);
++  return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Integer> (*NativePropertyQuery)
++    (v8::Local<v8::String>, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Value> IndexGetterCallbackWrapper(
++    uint32_t index, const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyGetterIndex)
++              .As<v8::External>()->Value()));
++  callback(index, cbinfo);
++  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Value> (*NativeIndexGetter)
++    (uint32_t, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Value> IndexSetterCallbackWrapper(
++    uint32_t index
++  , v8::Local<v8::Value> value
++  , const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Value>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertySetterIndex)
++              .As<v8::External>()->Value()));
++  callback(index, value, cbinfo);
++  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Value> (*NativeIndexSetter)
++    (uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper(
++    const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Array>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyEnumeratorIndex)
++              .As<v8::External>()->Value()));
++  callback(cbinfo);
++  return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Array> (*NativeIndexEnumerator)
++    (const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper(
++    uint32_t index, const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Boolean>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyDeleterIndex)
++              .As<v8::External>()->Value()));
++  callback(index, cbinfo);
++  return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter)
++    (uint32_t, const v8::AccessorInfo &);
++
++static
++v8::Handle<v8::Integer> IndexQueryCallbackWrapper(
++    uint32_t index, const v8::AccessorInfo &info) {
++  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
++  PropertyCallbackInfo<v8::Integer>
++      cbinfo(info, obj->GetInternalField(kDataIndex));
++  IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
++      reinterpret_cast<intptr_t>(
++          obj->GetInternalField(kIndexPropertyQueryIndex)
++              .As<v8::External>()->Value()));
++  callback(index, cbinfo);
++  return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
++}
++
++typedef v8::Handle<v8::Integer> (*NativeIndexQuery)
++    (uint32_t, const v8::AccessorInfo &);
++}  // end of namespace imp
++
++#endif  // NAN_CALLBACKS_PRE_12_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c0b327294644045c2c7611d11e1cd83dd3ccab70
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,72 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_CONVERTERS_H_
++#define NAN_CONVERTERS_H_
++
++namespace imp {
++template<typename T> struct ToFactoryBase {
++  typedef MaybeLocal<T> return_t;
++};
++template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; };
++
++template<typename T> struct ToFactory;
++
++template<>
++struct ToFactory<v8::Function> : ToFactoryBase<v8::Function> {
++  static inline return_t convert(v8::Local<v8::Value> val) {
++    if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal<v8::Function>();
++    return MaybeLocal<v8::Function>(val.As<v8::Function>());
++  }
++};
++
++#define X(TYPE)                                                                \
++    template<>                                                                 \
++    struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> {                     \
++      static inline return_t convert(v8::Local<v8::Value> val);                \
++    };
++
++X(Boolean)
++X(Number)
++X(String)
++X(Object)
++X(Integer)
++X(Uint32)
++X(Int32)
++
++#undef X
++
++#define X(TYPE)                                                                \
++    template<>                                                                 \
++    struct ToFactory<TYPE> : ValueFactoryBase<TYPE> {                          \
++      static inline return_t convert(v8::Local<v8::Value> val);                \
++    };
++
++X(bool)
++X(double)
++X(int64_t)
++X(uint32_t)
++X(int32_t)
++
++#undef X
++}  // end of namespace imp
++
++template<typename T>
++inline
++typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) {
++  return imp::ToFactory<T>::convert(val);
++}
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++# include "nan_converters_43_inl.h"
++#else
++# include "nan_converters_pre_43_inl.h"
++#endif
++
++#endif  // NAN_CONVERTERS_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..41b72deb3a25e9afbc4eb857b182e9d8d78843bd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,68 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_CONVERTERS_43_INL_H_
++#define NAN_CONVERTERS_43_INL_H_
++
++#define X(TYPE)                                                                \
++imp::ToFactory<v8::TYPE>::return_t                                             \
++imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) {                  \
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
++  v8::EscapableHandleScope scope(isolate);                                     \
++  return scope.Escape(                                                         \
++      val->To ## TYPE(isolate->GetCurrentContext())                            \
++          .FromMaybe(v8::Local<v8::TYPE>()));                                  \
++}
++
++X(Number)
++X(String)
++X(Object)
++X(Integer)
++X(Uint32)
++X(Int32)
++// V8 <= 7.0
++#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0)
++X(Boolean)
++#else
++imp::ToFactory<v8::Boolean>::return_t                                          \
++imp::ToFactory<v8::Boolean>::convert(v8::Local<v8::Value> val) {               \
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
++  v8::EscapableHandleScope scope(isolate);                                     \
++  return scope.Escape(val->ToBoolean(isolate));                                \
++}
++#endif
++
++#undef X
++
++#define X(TYPE, NAME)                                                          \
++imp::ToFactory<TYPE>::return_t                                                 \
++imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) {                      \
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
++  v8::HandleScope scope(isolate);                                              \
++  return val->NAME ## Value(isolate->GetCurrentContext());                     \
++}
++
++X(double, Number)
++X(int64_t, Integer)
++X(uint32_t, Uint32)
++X(int32_t, Int32)
++// V8 <= 7.0
++#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0)
++X(bool, Boolean)
++#else
++imp::ToFactory<bool>::return_t                                                 \
++imp::ToFactory<bool>::convert(v8::Local<v8::Value> val) {                      \
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
++  v8::HandleScope scope(isolate);                                              \
++  return Just<bool>(val->BooleanValue(isolate));                               \
++}
++#endif
++
++#undef X
++
++#endif  // NAN_CONVERTERS_43_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..ae0518aa33d0851cd08dfd8a3bb321508e02b64a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,42 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_CONVERTERS_PRE_43_INL_H_
++#define NAN_CONVERTERS_PRE_43_INL_H_
++
++#define X(TYPE)                                                                \
++imp::ToFactory<v8::TYPE>::return_t                                             \
++imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) {                  \
++  return val->To ## TYPE();                                                    \
++}
++
++X(Boolean)
++X(Number)
++X(String)
++X(Object)
++X(Integer)
++X(Uint32)
++X(Int32)
++
++#undef X
++
++#define X(TYPE, NAME)                                                          \
++imp::ToFactory<TYPE>::return_t                                                 \
++imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) {                      \
++  return Just(val->NAME ## Value());                                           \
++}
++
++X(bool, Boolean)
++X(double, Number)
++X(int64_t, Integer)
++X(uint32_t, Uint32)
++X(int32_t, Int32)
++
++#undef X
++
++#endif  // NAN_CONVERTERS_PRE_43_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d710ef2293d93746e87b671e7c5e8577784f9e27
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,29 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_
++#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_
++
++namespace imp {
++
++inline Maybe<bool> DefineOwnPropertyHelper(
++    v8::PropertyAttribute current
++  , v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key
++  , v8::Handle<v8::Value> value
++  , v8::PropertyAttribute attribs = v8::None) {
++  return !(current & v8::DontDelete) ||                     // configurable OR
++                  (!(current & v8::ReadOnly) &&             // writable AND
++                   !((attribs ^ current) & ~v8::ReadOnly))  // same excluding RO
++             ? Just<bool>(obj->ForceSet(key, value, attribs))
++             : Nothing<bool>();
++}
++
++}  // end of namespace imp
++
++#endif  // NAN_DEFINE_OWN_PROPERTY_HELPER_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..255293ac2deb689d0e15644c4645780b09ad0e3b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,430 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_IMPLEMENTATION_12_INL_H_
++#define NAN_IMPLEMENTATION_12_INL_H_
++//==============================================================================
++// node v0.11 implementation
++//==============================================================================
++
++namespace imp {
++
++//=== Array ====================================================================
++
++Factory<v8::Array>::return_t
++Factory<v8::Array>::New() {
++  return v8::Array::New(v8::Isolate::GetCurrent());
++}
++
++Factory<v8::Array>::return_t
++Factory<v8::Array>::New(int length) {
++  return v8::Array::New(v8::Isolate::GetCurrent(), length);
++}
++
++//=== Boolean ==================================================================
++
++Factory<v8::Boolean>::return_t
++Factory<v8::Boolean>::New(bool value) {
++  return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
++}
++
++//=== Boolean Object ===========================================================
++
++Factory<v8::BooleanObject>::return_t
++Factory<v8::BooleanObject>::New(bool value) {
++#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
++  return v8::BooleanObject::New(
++    v8::Isolate::GetCurrent(), value).As<v8::BooleanObject>();
++#else
++  return v8::BooleanObject::New(value).As<v8::BooleanObject>();
++#endif
++}
++
++//=== Context ==================================================================
++
++Factory<v8::Context>::return_t
++Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
++                         , v8::Local<v8::ObjectTemplate> tmpl
++                         , v8::Local<v8::Value> obj) {
++  return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj);
++}
++
++//=== Date =====================================================================
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++Factory<v8::Date>::return_t
++Factory<v8::Date>::New(double value) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value)
++      .FromMaybe(v8::Local<v8::Value>()).As<v8::Date>());
++}
++#else
++Factory<v8::Date>::return_t
++Factory<v8::Date>::New(double value) {
++  return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>();
++}
++#endif
++
++//=== External =================================================================
++
++Factory<v8::External>::return_t
++Factory<v8::External>::New(void * value) {
++  return v8::External::New(v8::Isolate::GetCurrent(), value);
++}
++
++//=== Function =================================================================
++
++Factory<v8::Function>::return_t
++Factory<v8::Function>::New( FunctionCallback callback
++                          , v8::Local<v8::Value> data) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
++  tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
++  v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
++
++  obj->SetInternalField(
++      imp::kFunctionIndex
++    , v8::External::New(isolate, reinterpret_cast<void *>(callback)));
++
++  v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
++
++  if (!val.IsEmpty()) {
++    obj->SetInternalField(imp::kDataIndex, val);
++  }
++
++#if NODE_MAJOR_VERSION >= 10
++  v8::Local<v8::Context> context = isolate->GetCurrentContext();
++  v8::Local<v8::Function> function =
++      v8::Function::New(context, imp::FunctionCallbackWrapper, obj)
++      .ToLocalChecked();
++#else
++  v8::Local<v8::Function> function =
++      v8::Function::New(isolate, imp::FunctionCallbackWrapper, obj);
++#endif
++
++  return scope.Escape(function);
++}
++
++//=== Function Template ========================================================
++
++Factory<v8::FunctionTemplate>::return_t
++Factory<v8::FunctionTemplate>::New( FunctionCallback callback
++                                  , v8::Local<v8::Value> data
++                                  , v8::Local<v8::Signature> signature) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  if (callback) {
++    v8::EscapableHandleScope scope(isolate);
++    v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
++    tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
++    v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
++
++    obj->SetInternalField(
++        imp::kFunctionIndex
++      , v8::External::New(isolate, reinterpret_cast<void *>(callback)));
++    v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
++
++    if (!val.IsEmpty()) {
++      obj->SetInternalField(imp::kDataIndex, val);
++    }
++
++    return scope.Escape(v8::FunctionTemplate::New( isolate
++                                    , imp::FunctionCallbackWrapper
++                                    , obj
++                                    , signature));
++  } else {
++    return v8::FunctionTemplate::New(isolate, 0, data, signature);
++  }
++}
++
++//=== Number ===================================================================
++
++Factory<v8::Number>::return_t
++Factory<v8::Number>::New(double value) {
++  return v8::Number::New(v8::Isolate::GetCurrent(), value);
++}
++
++//=== Number Object ============================================================
++
++Factory<v8::NumberObject>::return_t
++Factory<v8::NumberObject>::New(double value) {
++  return v8::NumberObject::New( v8::Isolate::GetCurrent()
++                              , value).As<v8::NumberObject>();
++}
++
++//=== Integer, Int32 and Uint32 ================================================
++
++template <typename T>
++typename IntegerFactory<T>::return_t
++IntegerFactory<T>::New(int32_t value) {
++  return To<T>(T::New(v8::Isolate::GetCurrent(), value));
++}
++
++template <typename T>
++typename IntegerFactory<T>::return_t
++IntegerFactory<T>::New(uint32_t value) {
++  return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
++}
++
++Factory<v8::Uint32>::return_t
++Factory<v8::Uint32>::New(int32_t value) {
++  return To<v8::Uint32>(
++      v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
++}
++
++Factory<v8::Uint32>::return_t
++Factory<v8::Uint32>::New(uint32_t value) {
++  return To<v8::Uint32>(
++      v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
++}
++
++//=== Object ===================================================================
++
++Factory<v8::Object>::return_t
++Factory<v8::Object>::New() {
++  return v8::Object::New(v8::Isolate::GetCurrent());
++}
++
++//=== Object Template ==========================================================
++
++Factory<v8::ObjectTemplate>::return_t
++Factory<v8::ObjectTemplate>::New() {
++  return v8::ObjectTemplate::New(v8::Isolate::GetCurrent());
++}
++
++//=== RegExp ===================================================================
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++Factory<v8::RegExp>::return_t
++Factory<v8::RegExp>::New(
++    v8::Local<v8::String> pattern
++  , v8::RegExp::Flags flags) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(
++      v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags)
++          .FromMaybe(v8::Local<v8::RegExp>()));
++}
++#else
++Factory<v8::RegExp>::return_t
++Factory<v8::RegExp>::New(
++    v8::Local<v8::String> pattern
++  , v8::RegExp::Flags flags) {
++  return v8::RegExp::New(pattern, flags);
++}
++#endif
++
++//=== Script ===================================================================
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++Factory<v8::Script>::return_t
++Factory<v8::Script>::New( v8::Local<v8::String> source) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  v8::ScriptCompiler::Source src(source);
++  return scope.Escape(
++      v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src)
++          .FromMaybe(v8::Local<v8::Script>()));
++}
++
++Factory<v8::Script>::return_t
++Factory<v8::Script>::New( v8::Local<v8::String> source
++                        , v8::ScriptOrigin const& origin) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  v8::ScriptCompiler::Source src(source, origin);
++  return scope.Escape(
++      v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src)
++          .FromMaybe(v8::Local<v8::Script>()));
++}
++#else
++Factory<v8::Script>::return_t
++Factory<v8::Script>::New( v8::Local<v8::String> source) {
++  v8::ScriptCompiler::Source src(source);
++  return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
++}
++
++Factory<v8::Script>::return_t
++Factory<v8::Script>::New( v8::Local<v8::String> source
++                        , v8::ScriptOrigin const& origin) {
++  v8::ScriptCompiler::Source src(source, origin);
++  return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
++}
++#endif
++
++//=== Signature ================================================================
++
++Factory<v8::Signature>::return_t
++Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
++  return v8::Signature::New(v8::Isolate::GetCurrent(), receiver);
++}
++
++//=== String ===================================================================
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New() {
++  return v8::String::Empty(v8::Isolate::GetCurrent());
++}
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++Factory<v8::String>::return_t
++Factory<v8::String>::New(const char * value, int length) {
++  return v8::String::NewFromUtf8(
++      v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(std::string const& value) {
++  assert(value.size() <= INT_MAX && "string too long");
++  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
++      value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size()));
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(const uint16_t * value, int length) {
++  return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
++        v8::NewStringType::kNormal, length);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
++  return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(ExternalOneByteStringResource * value) {
++  return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value);
++}
++#else
++Factory<v8::String>::return_t
++Factory<v8::String>::New(const char * value, int length) {
++  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value,
++                                 v8::String::kNormalString, length);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(
++    std::string const& value) /* NOLINT(build/include_what_you_use) */ {
++  assert(value.size() <= INT_MAX && "string too long");
++  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(),
++                                 v8::String::kNormalString,
++                                 static_cast<int>(value.size()));
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(const uint16_t * value, int length) {
++  return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
++                                    v8::String::kNormalString, length);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
++  return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(ExternalOneByteStringResource * value) {
++  return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
++}
++#endif
++
++//=== String Object ============================================================
++
++// See https://github.com/nodejs/nan/pull/811#discussion_r224594980.
++// Disable the warning as there is no way around it.
++// TODO(bnoordhuis) Use isolate-based version in Node.js v12.
++Factory<v8::StringObject>::return_t
++Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
++// V8 > 7.0
++#if V8_MAJOR_VERSION > 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION > 0)
++  return v8::StringObject::New(v8::Isolate::GetCurrent(), value)
++      .As<v8::StringObject>();
++#else
++#ifdef _MSC_VER
++#pragma warning(push)
++#pragma warning(disable : 4996)
++#endif
++#ifdef __GNUC__
++#pragma GCC diagnostic push
++#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
++#endif
++  return v8::StringObject::New(value).As<v8::StringObject>();
++#ifdef __GNUC__
++#pragma GCC diagnostic pop
++#endif
++#ifdef _MSC_VER
++#pragma warning(pop)
++#endif
++#endif
++}
++
++//=== Unbound Script ===========================================================
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++Factory<v8::UnboundScript>::return_t
++Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
++  v8::ScriptCompiler::Source src(source);
++  return v8::ScriptCompiler::CompileUnboundScript(
++      v8::Isolate::GetCurrent(), &src);
++}
++
++Factory<v8::UnboundScript>::return_t
++Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
++                               , v8::ScriptOrigin const& origin) {
++  v8::ScriptCompiler::Source src(source, origin);
++  return v8::ScriptCompiler::CompileUnboundScript(
++      v8::Isolate::GetCurrent(), &src);
++}
++#else
++Factory<v8::UnboundScript>::return_t
++Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
++  v8::ScriptCompiler::Source src(source);
++  return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
++}
++
++Factory<v8::UnboundScript>::return_t
++Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
++                               , v8::ScriptOrigin const& origin) {
++  v8::ScriptCompiler::Source src(source, origin);
++  return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
++}
++#endif
++
++}  // end of namespace imp
++
++//=== Presistents and Handles ==================================================
++
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++template <typename T>
++inline v8::Local<T> New(v8::Handle<T> h) {
++  return v8::Local<T>::New(v8::Isolate::GetCurrent(), h);
++}
++#endif
++
++template <typename T, typename M>
++inline v8::Local<T> New(v8::Persistent<T, M> const& p) {
++  return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
++}
++
++template <typename T, typename M>
++inline v8::Local<T> New(Persistent<T, M> const& p) {
++  return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
++}
++
++template <typename T>
++inline v8::Local<T> New(Global<T> const& p) {
++  return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
++}
++
++#endif  // NAN_IMPLEMENTATION_12_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..1472421afa76883abdc6077d92b7c5d3b6000e77
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,263 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_
++#define NAN_IMPLEMENTATION_PRE_12_INL_H_
++
++//==============================================================================
++// node v0.10 implementation
++//==============================================================================
++
++namespace imp {
++
++//=== Array ====================================================================
++
++Factory<v8::Array>::return_t
++Factory<v8::Array>::New() {
++  return v8::Array::New();
++}
++
++Factory<v8::Array>::return_t
++Factory<v8::Array>::New(int length) {
++  return v8::Array::New(length);
++}
++
++//=== Boolean ==================================================================
++
++Factory<v8::Boolean>::return_t
++Factory<v8::Boolean>::New(bool value) {
++  return v8::Boolean::New(value)->ToBoolean();
++}
++
++//=== Boolean Object ===========================================================
++
++Factory<v8::BooleanObject>::return_t
++Factory<v8::BooleanObject>::New(bool value) {
++  return v8::BooleanObject::New(value).As<v8::BooleanObject>();
++}
++
++//=== Context ==================================================================
++
++Factory<v8::Context>::return_t
++Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
++                         , v8::Local<v8::ObjectTemplate> tmpl
++                         , v8::Local<v8::Value> obj) {
++  v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj);
++  v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx);
++  ctx.Dispose();
++  return lctx;
++}
++
++//=== Date =====================================================================
++
++Factory<v8::Date>::return_t
++Factory<v8::Date>::New(double value) {
++  return v8::Date::New(value).As<v8::Date>();
++}
++
++//=== External =================================================================
++
++Factory<v8::External>::return_t
++Factory<v8::External>::New(void * value) {
++  return v8::External::New(value);
++}
++
++//=== Function =================================================================
++
++Factory<v8::Function>::return_t
++Factory<v8::Function>::New( FunctionCallback callback
++                          , v8::Local<v8::Value> data) {
++  v8::HandleScope scope;
++
++  return scope.Close(Factory<v8::FunctionTemplate>::New(
++                         callback, data, v8::Local<v8::Signature>())
++                         ->GetFunction());
++}
++
++
++//=== FunctionTemplate =========================================================
++
++Factory<v8::FunctionTemplate>::return_t
++Factory<v8::FunctionTemplate>::New( FunctionCallback callback
++                                  , v8::Local<v8::Value> data
++                                  , v8::Local<v8::Signature> signature) {
++  if (callback) {
++    v8::HandleScope scope;
++
++    v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New();
++    tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
++    v8::Local<v8::Object> obj = tpl->NewInstance();
++
++    obj->SetInternalField(
++        imp::kFunctionIndex
++      , v8::External::New(reinterpret_cast<void *>(callback)));
++
++    v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data);
++
++    if (!val.IsEmpty()) {
++      obj->SetInternalField(imp::kDataIndex, val);
++    }
++
++    // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find
++    // a way. Have at it though...
++    return scope.Close(
++        v8::FunctionTemplate::New(imp::FunctionCallbackWrapper
++                                 , obj
++                                 , signature));
++  } else {
++    return v8::FunctionTemplate::New(0, data, signature);
++  }
++}
++
++//=== Number ===================================================================
++
++Factory<v8::Number>::return_t
++Factory<v8::Number>::New(double value) {
++  return v8::Number::New(value);
++}
++
++//=== Number Object ============================================================
++
++Factory<v8::NumberObject>::return_t
++Factory<v8::NumberObject>::New(double value) {
++  return v8::NumberObject::New(value).As<v8::NumberObject>();
++}
++
++//=== Integer, Int32 and Uint32 ================================================
++
++template <typename T>
++typename IntegerFactory<T>::return_t
++IntegerFactory<T>::New(int32_t value) {
++  return To<T>(T::New(value));
++}
++
++template <typename T>
++typename IntegerFactory<T>::return_t
++IntegerFactory<T>::New(uint32_t value) {
++  return To<T>(T::NewFromUnsigned(value));
++}
++
++Factory<v8::Uint32>::return_t
++Factory<v8::Uint32>::New(int32_t value) {
++  return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
++}
++
++Factory<v8::Uint32>::return_t
++Factory<v8::Uint32>::New(uint32_t value) {
++  return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
++}
++
++
++//=== Object ===================================================================
++
++Factory<v8::Object>::return_t
++Factory<v8::Object>::New() {
++  return v8::Object::New();
++}
++
++//=== Object Template ==========================================================
++
++Factory<v8::ObjectTemplate>::return_t
++Factory<v8::ObjectTemplate>::New() {
++  return v8::ObjectTemplate::New();
++}
++
++//=== RegExp ===================================================================
++
++Factory<v8::RegExp>::return_t
++Factory<v8::RegExp>::New(
++    v8::Local<v8::String> pattern
++  , v8::RegExp::Flags flags) {
++  return v8::RegExp::New(pattern, flags);
++}
++
++//=== Script ===================================================================
++
++Factory<v8::Script>::return_t
++Factory<v8::Script>::New( v8::Local<v8::String> source) {
++  return v8::Script::New(source);
++}
++Factory<v8::Script>::return_t
++Factory<v8::Script>::New( v8::Local<v8::String> source
++                        , v8::ScriptOrigin const& origin) {
++  return v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin));
++}
++
++//=== Signature ================================================================
++
++Factory<v8::Signature>::return_t
++Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
++  return v8::Signature::New(receiver);
++}
++
++//=== String ===================================================================
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New() {
++  return v8::String::Empty();
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(const char * value, int length) {
++  return v8::String::New(value, length);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(
++    std::string const& value) /* NOLINT(build/include_what_you_use) */ {
++  assert(value.size() <= INT_MAX && "string too long");
++  return v8::String::New(value.data(), static_cast<int>(value.size()));
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(const uint16_t * value, int length) {
++  return v8::String::New(value, length);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
++  return v8::String::NewExternal(value);
++}
++
++Factory<v8::String>::return_t
++Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) {
++  return v8::String::NewExternal(value);
++}
++
++//=== String Object ============================================================
++
++Factory<v8::StringObject>::return_t
++Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
++  return v8::StringObject::New(value).As<v8::StringObject>();
++}
++
++}  // end of namespace imp
++
++//=== Presistents and Handles ==================================================
++
++template <typename T>
++inline v8::Local<T> New(v8::Handle<T> h) {
++  return v8::Local<T>::New(h);
++}
++
++template <typename T>
++inline v8::Local<T> New(v8::Persistent<T> const& p) {
++  return v8::Local<T>::New(p);
++}
++
++template <typename T, typename M>
++inline v8::Local<T> New(Persistent<T, M> const& p) {
++  return v8::Local<T>::New(p.persistent);
++}
++
++template <typename T>
++inline v8::Local<T> New(Global<T> const& p) {
++  return v8::Local<T>::New(p.persistent);
++}
++
++#endif  // NAN_IMPLEMENTATION_PRE_12_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..33ac8ba69a082f5be23ce56d4c2d2cc078cd7646
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,166 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_JSON_H_
++#define NAN_JSON_H_
++
++#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION
++#define NAN_JSON_H_NEED_PARSE 1
++#else
++#define NAN_JSON_H_NEED_PARSE 0
++#endif  // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION
++
++#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION
++#define NAN_JSON_H_NEED_STRINGIFY 0
++#else
++#define NAN_JSON_H_NEED_STRINGIFY 1
++#endif  // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION
++
++class JSON {
++ public:
++  JSON() {
++#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY
++    Nan::HandleScope scope;
++
++    Nan::MaybeLocal<v8::Value> maybe_global_json = Nan::Get(
++      Nan::GetCurrentContext()->Global(),
++      Nan::New("JSON").ToLocalChecked()
++    );
++
++    assert(!maybe_global_json.IsEmpty() && "global JSON is empty");
++    v8::Local<v8::Value> val_global_json = maybe_global_json.ToLocalChecked();
++
++    assert(val_global_json->IsObject() && "global JSON is not an object");
++    Nan::MaybeLocal<v8::Object> maybe_obj_global_json =
++      Nan::To<v8::Object>(val_global_json);
++
++    assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty");
++    v8::Local<v8::Object> global_json = maybe_obj_global_json.ToLocalChecked();
++
++#if NAN_JSON_H_NEED_PARSE
++    Nan::MaybeLocal<v8::Value> maybe_parse_method = Nan::Get(
++      global_json, Nan::New("parse").ToLocalChecked()
++    );
++
++    assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty");
++    v8::Local<v8::Value> parse_method = maybe_parse_method.ToLocalChecked();
++
++    assert(parse_method->IsFunction() && "JSON.parse is not a function");
++    parse_cb_.Reset(parse_method.As<v8::Function>());
++#endif  // NAN_JSON_H_NEED_PARSE
++
++#if NAN_JSON_H_NEED_STRINGIFY
++    Nan::MaybeLocal<v8::Value> maybe_stringify_method = Nan::Get(
++      global_json, Nan::New("stringify").ToLocalChecked()
++    );
++
++    assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty");
++    v8::Local<v8::Value> stringify_method =
++      maybe_stringify_method.ToLocalChecked();
++
++    assert(
++      stringify_method->IsFunction() && "JSON.stringify is not a function"
++    );
++    stringify_cb_.Reset(stringify_method.As<v8::Function>());
++#endif  // NAN_JSON_H_NEED_STRINGIFY
++#endif  // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY
++  }
++
++  inline
++  Nan::MaybeLocal<v8::Value> Parse(v8::Local<v8::String> json_string) {
++    Nan::EscapableHandleScope scope;
++#if NAN_JSON_H_NEED_PARSE
++    return scope.Escape(parse(json_string));
++#else
++    Nan::MaybeLocal<v8::Value> result;
++#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \
++    NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION
++    result = v8::JSON::Parse(json_string);
++#else
++#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION
++    v8::Local<v8::Context> context_or_isolate = Nan::GetCurrentContext();
++#else
++    v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent();
++#endif  // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION
++    result = v8::JSON::Parse(context_or_isolate, json_string);
++#endif  // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION &&
++        // NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION
++    if (result.IsEmpty()) return v8::Local<v8::Value>();
++    return scope.Escape(result.ToLocalChecked());
++#endif  // NAN_JSON_H_NEED_PARSE
++  }
++
++  inline
++  Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object) {
++    Nan::EscapableHandleScope scope;
++    Nan::MaybeLocal<v8::String> result =
++#if NAN_JSON_H_NEED_STRINGIFY
++      Nan::To<v8::String>(stringify(json_object));
++#else
++      v8::JSON::Stringify(Nan::GetCurrentContext(), json_object);
++#endif  // NAN_JSON_H_NEED_STRINGIFY
++    if (result.IsEmpty()) return v8::Local<v8::String>();
++    return scope.Escape(result.ToLocalChecked());
++  }
++
++  inline
++  Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object,
++    v8::Local<v8::String> gap) {
++    Nan::EscapableHandleScope scope;
++    Nan::MaybeLocal<v8::String> result =
++#if NAN_JSON_H_NEED_STRINGIFY
++      Nan::To<v8::String>(stringify(json_object, gap));
++#else
++      v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap);
++#endif  // NAN_JSON_H_NEED_STRINGIFY
++    if (result.IsEmpty()) return v8::Local<v8::String>();
++    return scope.Escape(result.ToLocalChecked());
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON)
++#if NAN_JSON_H_NEED_PARSE
++  Nan::Callback parse_cb_;
++#endif  // NAN_JSON_H_NEED_PARSE
++#if NAN_JSON_H_NEED_STRINGIFY
++  Nan::Callback stringify_cb_;
++#endif  // NAN_JSON_H_NEED_STRINGIFY
++
++#if NAN_JSON_H_NEED_PARSE
++  inline v8::Local<v8::Value> parse(v8::Local<v8::Value> arg) {
++    assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty");
++    AsyncResource resource("nan:JSON.parse");
++    return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local<v8::Value>());
++  }
++#endif  // NAN_JSON_H_NEED_PARSE
++
++#if NAN_JSON_H_NEED_STRINGIFY
++  inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg) {
++    assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty");
++    AsyncResource resource("nan:JSON.stringify");
++    return stringify_cb_.Call(1, &arg, &resource)
++        .FromMaybe(v8::Local<v8::Value>());
++  }
++
++  inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg,
++    v8::Local<v8::String> gap) {
++    assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty");
++
++    v8::Local<v8::Value> argv[] = {
++      arg,
++      Nan::Null(),
++      gap
++    };
++    AsyncResource resource("nan:JSON.stringify");
++    return stringify_cb_.Call(3, argv, &resource)
++        .FromMaybe(v8::Local<v8::Value>());
++  }
++#endif  // NAN_JSON_H_NEED_STRINGIFY
++};
++
++#endif  // NAN_JSON_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..c04ce30d2fa3bfb555c96754d93de64e8a83e36b
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,356 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_MAYBE_43_INL_H_
++#define NAN_MAYBE_43_INL_H_
++
++template<typename T>
++using MaybeLocal = v8::MaybeLocal<T>;
++
++inline
++MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(val->ToDetailString(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::String>()));
++}
++
++inline
++MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::Uint32>()));
++}
++
++inline
++Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return a->Equals(isolate->GetCurrentContext(), b);
++}
++
++inline
++MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(h->NewInstance(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::Object>()));
++}
++
++inline
++MaybeLocal<v8::Object> NewInstance(
++      v8::Local<v8::Function> h
++    , int argc
++    , v8::Local<v8::Value> argv[]) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv)
++                          .FromMaybe(v8::Local<v8::Object>()));
++}
++
++inline
++MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(h->NewInstance(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::Object>()));
++}
++
++
++inline MaybeLocal<v8::Function> GetFunction(
++    v8::Local<v8::FunctionTemplate> t) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(t->GetFunction(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::Function>()));
++}
++
++inline Maybe<bool> Set(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::Value> key
++  , v8::Local<v8::Value> value) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->Set(isolate->GetCurrentContext(), key, value);
++}
++
++inline Maybe<bool> Set(
++    v8::Local<v8::Object> obj
++  , uint32_t index
++  , v8::Local<v8::Value> value) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->Set(isolate->GetCurrentContext(), index, value);
++}
++
++#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION
++#include "nan_define_own_property_helper.h"  // NOLINT(build/include)
++#endif
++
++inline Maybe<bool> DefineOwnProperty(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key
++  , v8::Local<v8::Value> value
++  , v8::PropertyAttribute attribs = v8::None) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION
++  return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value,
++                                attribs);
++#else
++  Maybe<v8::PropertyAttribute> maybeCurrent =
++      obj->GetPropertyAttributes(isolate->GetCurrentContext(), key);
++  if (maybeCurrent.IsNothing()) {
++    return Nothing<bool>();
++  }
++  v8::PropertyAttribute current = maybeCurrent.FromJust();
++  return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs);
++#endif
++}
++
++NAN_DEPRECATED inline Maybe<bool> ForceSet(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::Value> key
++  , v8::Local<v8::Value> value
++  , v8::PropertyAttribute attribs = v8::None) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
++  return key->IsName()
++             ? obj->DefineOwnProperty(isolate->GetCurrentContext(),
++                                      key.As<v8::Name>(), value, attribs)
++             : Nothing<bool>();
++#else
++  return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);
++#endif
++}
++
++inline MaybeLocal<v8::Value> Get(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::Value> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(obj->Get(isolate->GetCurrentContext(), key)
++                          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline
++MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(obj->Get(isolate->GetCurrentContext(), index)
++                          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline v8::PropertyAttribute GetPropertyAttributes(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::Value> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key)
++      .FromJust();
++}
++
++inline Maybe<bool> Has(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->Has(isolate->GetCurrentContext(), key);
++}
++
++inline Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->Has(isolate->GetCurrentContext(), index);
++}
++
++inline Maybe<bool> Delete(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->Delete(isolate->GetCurrentContext(), key);
++}
++
++inline
++Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->Delete(isolate->GetCurrentContext(), index);
++}
++
++inline
++MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::Array>()));
++}
++
++inline
++MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::Array>()));
++}
++
++inline Maybe<bool> SetPrototype(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::Value> prototype) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->SetPrototype(isolate->GetCurrentContext(), prototype);
++}
++
++inline MaybeLocal<v8::String> ObjectProtoToString(
++    v8::Local<v8::Object> obj) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::String>()));
++}
++
++inline Maybe<bool> HasOwnProperty(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->HasOwnProperty(isolate->GetCurrentContext(), key);
++}
++
++inline Maybe<bool> HasRealNamedProperty(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key);
++}
++
++inline Maybe<bool> HasRealIndexedProperty(
++    v8::Local<v8::Object> obj
++  , uint32_t index) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index);
++}
++
++inline Maybe<bool> HasRealNamedCallbackProperty(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key);
++}
++
++inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain(
++                             isolate->GetCurrentContext(), key)
++                          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline MaybeLocal<v8::Value> GetRealNamedProperty(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::String> key) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(
++      obj->GetRealNamedProperty(isolate->GetCurrentContext(), key)
++          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline MaybeLocal<v8::Value> CallAsFunction(
++    v8::Local<v8::Object> obj
++  , v8::Local<v8::Object> recv
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(
++      obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv)
++          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline MaybeLocal<v8::Value> CallAsConstructor(
++    v8::Local<v8::Object> obj
++  , int argc, v8::Local<v8::Value> argv[]) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(
++      obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv)
++          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++inline
++MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext())
++                          .FromMaybe(v8::Local<v8::String>()));
++}
++
++inline Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return msg->GetLineNumber(isolate->GetCurrentContext());
++}
++
++inline Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return msg->GetStartColumn(isolate->GetCurrentContext());
++}
++
++inline Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::HandleScope scope(isolate);
++  return msg->GetEndColumn(isolate->GetCurrentContext());
++}
++
++inline MaybeLocal<v8::Object> CloneElementAt(
++    v8::Local<v8::Array> array
++  , uint32_t index) {
++#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  v8::Local<v8::Context> context = isolate->GetCurrentContext();
++  v8::Local<v8::Value> elem;
++  v8::Local<v8::Object> obj;
++  if (!array->Get(context, index).ToLocal(&elem)) {
++    return scope.Escape(obj);
++  }
++  if (!elem->ToObject(context).ToLocal(&obj)) {
++    return scope.Escape(v8::Local<v8::Object>());
++  }
++  return scope.Escape(obj->Clone());
++#else
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index)
++                          .FromMaybe(v8::Local<v8::Object>()));
++#endif
++}
++
++inline MaybeLocal<v8::Value> Call(
++    v8::Local<v8::Function> fun
++  , v8::Local<v8::Object> recv
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv)
++                          .FromMaybe(v8::Local<v8::Value>()));
++}
++
++#endif  // NAN_MAYBE_43_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..83325ae0897f95f2fe5354e9ab720796a7cefd7c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,268 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_MAYBE_PRE_43_INL_H_
++#define NAN_MAYBE_PRE_43_INL_H_
++
++template<typename T>
++class MaybeLocal {
++ public:
++  inline MaybeLocal() : val_(v8::Local<T>()) {}
++
++  template<typename S>
++# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
++  inline
++  MaybeLocal(v8::Local<S> that) : val_(that) {}  // NOLINT(runtime/explicit)
++# else
++  inline
++  MaybeLocal(v8::Local<S> that) :  // NOLINT(runtime/explicit)
++      val_(*reinterpret_cast<v8::Local<T>*>(&that)) {}
++# endif
++
++  inline bool IsEmpty() const { return val_.IsEmpty(); }
++
++  template<typename S>
++  inline bool ToLocal(v8::Local<S> *out) const {
++    *out = val_;
++    return !IsEmpty();
++  }
++
++  inline v8::Local<T> ToLocalChecked() const {
++#if defined(V8_ENABLE_CHECKS)
++    assert(!IsEmpty() && "ToLocalChecked is Empty");
++#endif  // V8_ENABLE_CHECKS
++    return val_;
++  }
++
++  template<typename S>
++  inline v8::Local<S> FromMaybe(v8::Local<S> default_value) const {
++    return IsEmpty() ? default_value : v8::Local<S>(val_);
++  }
++
++ private:
++  v8::Local<T> val_;
++};
++
++inline
++MaybeLocal<v8::String> ToDetailString(v8::Handle<v8::Value> val) {
++  return MaybeLocal<v8::String>(val->ToDetailString());
++}
++
++inline
++MaybeLocal<v8::Uint32> ToArrayIndex(v8::Handle<v8::Value> val) {
++  return MaybeLocal<v8::Uint32>(val->ToArrayIndex());
++}
++
++inline
++Maybe<bool> Equals(v8::Handle<v8::Value> a, v8::Handle<v8::Value>(b)) {
++  return Just<bool>(a->Equals(b));
++}
++
++inline
++MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::Function> h) {
++  return MaybeLocal<v8::Object>(h->NewInstance());
++}
++
++inline
++MaybeLocal<v8::Object> NewInstance(
++      v8::Local<v8::Function> h
++    , int argc
++    , v8::Local<v8::Value> argv[]) {
++  return MaybeLocal<v8::Object>(h->NewInstance(argc, argv));
++}
++
++inline
++MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::ObjectTemplate> h) {
++  return MaybeLocal<v8::Object>(h->NewInstance());
++}
++
++inline
++MaybeLocal<v8::Function> GetFunction(v8::Handle<v8::FunctionTemplate> t) {
++  return MaybeLocal<v8::Function>(t->GetFunction());
++}
++
++inline Maybe<bool> Set(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::Value> key
++  , v8::Handle<v8::Value> value) {
++  return Just<bool>(obj->Set(key, value));
++}
++
++inline Maybe<bool> Set(
++    v8::Handle<v8::Object> obj
++  , uint32_t index
++  , v8::Handle<v8::Value> value) {
++  return Just<bool>(obj->Set(index, value));
++}
++
++#include "nan_define_own_property_helper.h"  // NOLINT(build/include)
++
++inline Maybe<bool> DefineOwnProperty(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key
++  , v8::Handle<v8::Value> value
++  , v8::PropertyAttribute attribs = v8::None) {
++  v8::PropertyAttribute current = obj->GetPropertyAttributes(key);
++  return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs);
++}
++
++NAN_DEPRECATED inline Maybe<bool> ForceSet(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::Value> key
++  , v8::Handle<v8::Value> value
++  , v8::PropertyAttribute attribs = v8::None) {
++  return Just<bool>(obj->ForceSet(key, value, attribs));
++}
++
++inline MaybeLocal<v8::Value> Get(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::Value> key) {
++  return MaybeLocal<v8::Value>(obj->Get(key));
++}
++
++inline MaybeLocal<v8::Value> Get(
++    v8::Handle<v8::Object> obj
++  , uint32_t index) {
++  return MaybeLocal<v8::Value>(obj->Get(index));
++}
++
++inline Maybe<v8::PropertyAttribute> GetPropertyAttributes(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::Value> key) {
++  return Just<v8::PropertyAttribute>(obj->GetPropertyAttributes(key));
++}
++
++inline Maybe<bool> Has(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return Just<bool>(obj->Has(key));
++}
++
++inline Maybe<bool> Has(
++    v8::Handle<v8::Object> obj
++  , uint32_t index) {
++  return Just<bool>(obj->Has(index));
++}
++
++inline Maybe<bool> Delete(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return Just<bool>(obj->Delete(key));
++}
++
++inline Maybe<bool> Delete(
++    v8::Handle<v8::Object> obj
++  , uint32_t index) {
++  return Just<bool>(obj->Delete(index));
++}
++
++inline
++MaybeLocal<v8::Array> GetPropertyNames(v8::Handle<v8::Object> obj) {
++  return MaybeLocal<v8::Array>(obj->GetPropertyNames());
++}
++
++inline
++MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Handle<v8::Object> obj) {
++  return MaybeLocal<v8::Array>(obj->GetOwnPropertyNames());
++}
++
++inline Maybe<bool> SetPrototype(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::Value> prototype) {
++  return Just<bool>(obj->SetPrototype(prototype));
++}
++
++inline MaybeLocal<v8::String> ObjectProtoToString(
++    v8::Handle<v8::Object> obj) {
++  return MaybeLocal<v8::String>(obj->ObjectProtoToString());
++}
++
++inline Maybe<bool> HasOwnProperty(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return Just<bool>(obj->HasOwnProperty(key));
++}
++
++inline Maybe<bool> HasRealNamedProperty(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return Just<bool>(obj->HasRealNamedProperty(key));
++}
++
++inline Maybe<bool> HasRealIndexedProperty(
++    v8::Handle<v8::Object> obj
++  , uint32_t index) {
++  return Just<bool>(obj->HasRealIndexedProperty(index));
++}
++
++inline Maybe<bool> HasRealNamedCallbackProperty(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return Just<bool>(obj->HasRealNamedCallbackProperty(key));
++}
++
++inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return MaybeLocal<v8::Value>(
++      obj->GetRealNamedPropertyInPrototypeChain(key));
++}
++
++inline MaybeLocal<v8::Value> GetRealNamedProperty(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::String> key) {
++  return MaybeLocal<v8::Value>(obj->GetRealNamedProperty(key));
++}
++
++inline MaybeLocal<v8::Value> CallAsFunction(
++    v8::Handle<v8::Object> obj
++  , v8::Handle<v8::Object> recv
++  , int argc
++  , v8::Handle<v8::Value> argv[]) {
++  return MaybeLocal<v8::Value>(obj->CallAsFunction(recv, argc, argv));
++}
++
++inline MaybeLocal<v8::Value> CallAsConstructor(
++    v8::Handle<v8::Object> obj
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  return MaybeLocal<v8::Value>(obj->CallAsConstructor(argc, argv));
++}
++
++inline
++MaybeLocal<v8::String> GetSourceLine(v8::Handle<v8::Message> msg) {
++  return MaybeLocal<v8::String>(msg->GetSourceLine());
++}
++
++inline Maybe<int> GetLineNumber(v8::Handle<v8::Message> msg) {
++  return Just<int>(msg->GetLineNumber());
++}
++
++inline Maybe<int> GetStartColumn(v8::Handle<v8::Message> msg) {
++  return Just<int>(msg->GetStartColumn());
++}
++
++inline Maybe<int> GetEndColumn(v8::Handle<v8::Message> msg) {
++  return Just<int>(msg->GetEndColumn());
++}
++
++inline MaybeLocal<v8::Object> CloneElementAt(
++    v8::Handle<v8::Array> array
++  , uint32_t index) {
++  return MaybeLocal<v8::Object>(array->CloneElementAt(index));
++}
++
++inline MaybeLocal<v8::Value> Call(
++    v8::Local<v8::Function> fun
++  , v8::Local<v8::Object> recv
++  , int argc
++  , v8::Local<v8::Value> argv[]) {
++  return MaybeLocal<v8::Value>(fun->Call(recv, argc, argv));
++}
++
++#endif  // NAN_MAYBE_PRE_43_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cdf8bbe40b9b72c39ee9d4f00bdfc8bb7be6f7f6
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,340 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_NEW_H_
++#define NAN_NEW_H_
++
++namespace imp {  // scnr
++
++// TODO(agnat): Generalize
++template <typename T> v8::Local<T> To(v8::Local<v8::Integer> i);
++
++template <>
++inline
++v8::Local<v8::Integer>
++To<v8::Integer>(v8::Local<v8::Integer> i) {
++  return Nan::To<v8::Integer>(i).ToLocalChecked();
++}
++
++template <>
++inline
++v8::Local<v8::Int32>
++To<v8::Int32>(v8::Local<v8::Integer> i) {
++  return Nan::To<v8::Int32>(i).ToLocalChecked();
++}
++
++template <>
++inline
++v8::Local<v8::Uint32>
++To<v8::Uint32>(v8::Local<v8::Integer> i) {
++  return Nan::To<v8::Uint32>(i).ToLocalChecked();
++}
++
++template <typename T> struct FactoryBase {
++  typedef v8::Local<T> return_t;
++};
++
++template <typename T> struct MaybeFactoryBase {
++  typedef MaybeLocal<T> return_t;
++};
++
++template <typename T> struct Factory;
++
++template <>
++struct Factory<v8::Array> : FactoryBase<v8::Array> {
++  static inline return_t New();
++  static inline return_t New(int length);
++};
++
++template <>
++struct Factory<v8::Boolean> : FactoryBase<v8::Boolean> {
++  static inline return_t New(bool value);
++};
++
++template <>
++struct Factory<v8::BooleanObject> : FactoryBase<v8::BooleanObject> {
++  static inline return_t New(bool value);
++};
++
++template <>
++struct Factory<v8::Context> : FactoryBase<v8::Context> {
++  static inline
++  return_t
++  New( v8::ExtensionConfiguration* extensions = NULL
++     , v8::Local<v8::ObjectTemplate> tmpl = v8::Local<v8::ObjectTemplate>()
++     , v8::Local<v8::Value> obj = v8::Local<v8::Value>());
++};
++
++template <>
++struct Factory<v8::Date> : MaybeFactoryBase<v8::Date> {
++  static inline return_t New(double value);
++};
++
++template <>
++struct Factory<v8::External> : FactoryBase<v8::External> {
++  static inline return_t New(void *value);
++};
++
++template <>
++struct Factory<v8::Function> : FactoryBase<v8::Function> {
++  static inline
++  return_t
++  New( FunctionCallback callback
++     , v8::Local<v8::Value> data = v8::Local<v8::Value>());
++};
++
++template <>
++struct Factory<v8::FunctionTemplate> : FactoryBase<v8::FunctionTemplate> {
++  static inline
++  return_t
++  New( FunctionCallback callback = NULL
++     , v8::Local<v8::Value> data = v8::Local<v8::Value>()
++     , v8::Local<v8::Signature> signature = v8::Local<v8::Signature>());
++};
++
++template <>
++struct Factory<v8::Number> : FactoryBase<v8::Number> {
++  static inline return_t New(double value);
++};
++
++template <>
++struct Factory<v8::NumberObject> : FactoryBase<v8::NumberObject> {
++  static inline return_t New(double value);
++};
++
++template <typename T>
++struct IntegerFactory : FactoryBase<T> {
++  typedef typename FactoryBase<T>::return_t return_t;
++  static inline return_t New(int32_t value);
++  static inline return_t New(uint32_t value);
++};
++
++template <>
++struct Factory<v8::Integer> : IntegerFactory<v8::Integer> {};
++
++template <>
++struct Factory<v8::Int32> : IntegerFactory<v8::Int32> {};
++
++template <>
++struct Factory<v8::Uint32> : FactoryBase<v8::Uint32> {
++  static inline return_t New(int32_t value);
++  static inline return_t New(uint32_t value);
++};
++
++template <>
++struct Factory<v8::Object> : FactoryBase<v8::Object> {
++  static inline return_t New();
++};
++
++template <>
++struct Factory<v8::ObjectTemplate> : FactoryBase<v8::ObjectTemplate> {
++  static inline return_t New();
++};
++
++template <>
++struct Factory<v8::RegExp> : MaybeFactoryBase<v8::RegExp> {
++  static inline return_t New(
++      v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
++};
++
++template <>
++struct Factory<v8::Script> : MaybeFactoryBase<v8::Script> {
++  static inline return_t New( v8::Local<v8::String> source);
++  static inline return_t New( v8::Local<v8::String> source
++                            , v8::ScriptOrigin const& origin);
++};
++
++template <>
++struct Factory<v8::Signature> : FactoryBase<v8::Signature> {
++  typedef v8::Local<v8::FunctionTemplate> FTH;
++  static inline return_t New(FTH receiver = FTH());
++};
++
++template <>
++struct Factory<v8::String> : MaybeFactoryBase<v8::String> {
++  static inline return_t New();
++  static inline return_t New(const char *value, int length = -1);
++  static inline return_t New(const uint16_t *value, int length = -1);
++  static inline return_t New(std::string const& value);
++
++  static inline return_t New(v8::String::ExternalStringResource * value);
++  static inline return_t New(ExternalOneByteStringResource * value);
++};
++
++template <>
++struct Factory<v8::StringObject> : FactoryBase<v8::StringObject> {
++  static inline return_t New(v8::Local<v8::String> value);
++};
++
++}  // end of namespace imp
++
++#if (NODE_MODULE_VERSION >= 12)
++
++namespace imp {
++
++template <>
++struct Factory<v8::UnboundScript> : MaybeFactoryBase<v8::UnboundScript> {
++  static inline return_t New( v8::Local<v8::String> source);
++  static inline return_t New( v8::Local<v8::String> source
++                            , v8::ScriptOrigin const& origin);
++};
++
++}  // end of namespace imp
++
++# include "nan_implementation_12_inl.h"
++
++#else  // NODE_MODULE_VERSION >= 12
++
++# include "nan_implementation_pre_12_inl.h"
++
++#endif
++
++//=== API ======================================================================
++
++template <typename T>
++typename imp::Factory<T>::return_t
++New() {
++  return imp::Factory<T>::New();
++}
++
++template <typename T, typename A0>
++typename imp::Factory<T>::return_t
++New(A0 arg0) {
++  return imp::Factory<T>::New(arg0);
++}
++
++template <typename T, typename A0, typename A1>
++typename imp::Factory<T>::return_t
++New(A0 arg0, A1 arg1) {
++  return imp::Factory<T>::New(arg0, arg1);
++}
++
++template <typename T, typename A0, typename A1, typename A2>
++typename imp::Factory<T>::return_t
++New(A0 arg0, A1 arg1, A2 arg2) {
++  return imp::Factory<T>::New(arg0, arg1, arg2);
++}
++
++template <typename T, typename A0, typename A1, typename A2, typename A3>
++typename imp::Factory<T>::return_t
++New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) {
++  return imp::Factory<T>::New(arg0, arg1, arg2, arg3);
++}
++
++// Note(agnat): When passing overloaded function pointers to template functions
++// as generic arguments the compiler needs help in picking the right overload.
++// These two functions handle New<Function> and New<FunctionTemplate> with
++// all argument variations.
++
++// v8::Function and v8::FunctionTemplate with one or two arguments
++template <typename T>
++typename imp::Factory<T>::return_t
++New( FunctionCallback callback
++      , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
++    return imp::Factory<T>::New(callback, data);
++}
++
++// v8::Function and v8::FunctionTemplate with three arguments
++template <typename T, typename A2>
++typename imp::Factory<T>::return_t
++New( FunctionCallback callback
++      , v8::Local<v8::Value> data = v8::Local<v8::Value>()
++      , A2 a2 = A2()) {
++    return imp::Factory<T>::New(callback, data, a2);
++}
++
++// Convenience
++
++#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
++template <typename T> inline v8::Local<T> New(v8::Handle<T> h);
++#endif
++
++#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++template <typename T, typename M>
++    inline v8::Local<T> New(v8::Persistent<T, M> const& p);
++#else
++template <typename T> inline v8::Local<T> New(v8::Persistent<T> const& p);
++#endif
++template <typename T, typename M>
++inline v8::Local<T> New(Persistent<T, M> const& p);
++template <typename T>
++inline v8::Local<T> New(Global<T> const& p);
++
++inline
++imp::Factory<v8::Boolean>::return_t
++New(bool value) {
++  return New<v8::Boolean>(value);
++}
++
++inline
++imp::Factory<v8::Int32>::return_t
++New(int32_t value) {
++  return New<v8::Int32>(value);
++}
++
++inline
++imp::Factory<v8::Uint32>::return_t
++New(uint32_t value) {
++  return New<v8::Uint32>(value);
++}
++
++inline
++imp::Factory<v8::Number>::return_t
++New(double value) {
++  return New<v8::Number>(value);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(std::string const& value) {  // NOLINT(build/include_what_you_use)
++  return New<v8::String>(value);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(const char * value, int length) {
++  return New<v8::String>(value, length);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(const uint16_t * value, int length) {
++  return New<v8::String>(value, length);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(const char * value) {
++  return New<v8::String>(value);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(const uint16_t * value) {
++  return New<v8::String>(value);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(v8::String::ExternalStringResource * value) {
++  return New<v8::String>(value);
++}
++
++inline
++imp::Factory<v8::String>::return_t
++New(ExternalOneByteStringResource * value) {
++  return New<v8::String>(value);
++}
++
++inline
++imp::Factory<v8::RegExp>::return_t
++New(v8::Local<v8::String> pattern, v8::RegExp::Flags flags) {
++  return New<v8::RegExp>(pattern, flags);
++}
++
++#endif  // NAN_NEW_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..386affaa953f7749521f7898f85055ea63e1d207
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,156 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_OBJECT_WRAP_H_
++#define NAN_OBJECT_WRAP_H_
++
++class ObjectWrap {
++ public:
++  ObjectWrap() {
++    refs_ = 0;
++  }
++
++
++  virtual ~ObjectWrap() {
++    if (persistent().IsEmpty()) {
++      return;
++    }
++
++    persistent().ClearWeak();
++    persistent().Reset();
++  }
++
++
++  template <class T>
++  static inline T* Unwrap(v8::Local<v8::Object> object) {
++    assert(!object.IsEmpty());
++    assert(object->InternalFieldCount() > 0);
++    // Cast to ObjectWrap before casting to T.  A direct cast from void
++    // to T won't work right when T has more than one base class.
++    void* ptr = GetInternalFieldPointer(object, 0);
++    ObjectWrap* wrap = static_cast<ObjectWrap*>(ptr);
++    return static_cast<T*>(wrap);
++  }
++
++
++  inline v8::Local<v8::Object> handle() const {
++    return New(handle_);
++  }
++
++
++  inline Persistent<v8::Object>& persistent() {
++    return handle_;
++  }
++
++
++ protected:
++  inline void Wrap(v8::Local<v8::Object> object) {
++    assert(persistent().IsEmpty());
++    assert(object->InternalFieldCount() > 0);
++    SetInternalFieldPointer(object, 0, this);
++    persistent().Reset(object);
++    MakeWeak();
++  }
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++
++  inline void MakeWeak() {
++    persistent().v8::PersistentBase<v8::Object>::SetWeak(
++        this, WeakCallback, v8::WeakCallbackType::kParameter);
++#if NODE_MAJOR_VERSION < 10
++    // FIXME(bnoordhuis) Probably superfluous in older Node.js versions too.
++    persistent().MarkIndependent();
++#endif
++  }
++
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++
++  inline void MakeWeak() {
++    persistent().v8::PersistentBase<v8::Object>::SetWeak(this, WeakCallback);
++    persistent().MarkIndependent();
++  }
++
++#else
++
++  inline void MakeWeak() {
++    persistent().persistent.MakeWeak(this, WeakCallback);
++    persistent().MarkIndependent();
++  }
++
++#endif
++
++  /* Ref() marks the object as being attached to an event loop.
++   * Refed objects will not be garbage collected, even if
++   * all references are lost.
++   */
++  virtual void Ref() {
++    assert(!persistent().IsEmpty());
++    persistent().ClearWeak();
++    refs_++;
++  }
++
++  /* Unref() marks an object as detached from the event loop.  This is its
++   * default state.  When an object with a "weak" reference changes from
++   * attached to detached state it will be freed. Be careful not to access
++   * the object after making this call as it might be gone!
++   * (A "weak reference" means an object that only has a
++   * persistant handle.)
++   *
++   * DO NOT CALL THIS FROM DESTRUCTOR
++   */
++  virtual void Unref() {
++    assert(!persistent().IsEmpty());
++    assert(!persistent().IsWeak());
++    assert(refs_ > 0);
++    if (--refs_ == 0)
++      MakeWeak();
++  }
++
++  int refs_;  // ro
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap)
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++
++  static void
++  WeakCallback(v8::WeakCallbackInfo<ObjectWrap> const& info) {
++    ObjectWrap* wrap = info.GetParameter();
++    assert(wrap->refs_ == 0);
++    wrap->handle_.Reset();
++    delete wrap;
++  }
++
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++
++  static void
++  WeakCallback(v8::WeakCallbackData<v8::Object, ObjectWrap> const& data) {
++    ObjectWrap* wrap = data.GetParameter();
++    assert(wrap->refs_ == 0);
++    assert(wrap->handle_.IsNearDeath());
++    wrap->handle_.Reset();
++    delete wrap;
++  }
++
++#else
++
++  static void WeakCallback(v8::Persistent<v8::Value> value, void *data) {
++    ObjectWrap *wrap = static_cast<ObjectWrap*>(data);
++    assert(wrap->refs_ == 0);
++    assert(wrap->handle_.IsNearDeath());
++    wrap->handle_.Reset();
++    delete wrap;
++  }
++
++#endif
++  Persistent<v8::Object> handle_;
++};
++
++
++#endif  // NAN_OBJECT_WRAP_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d9649e867606c6356e393e9964b5607a08ea4e3a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,132 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_PERSISTENT_12_INL_H_
++#define NAN_PERSISTENT_12_INL_H_
++
++template<typename T, typename M> class Persistent :
++    public v8::Persistent<T, M> {
++ public:
++  inline Persistent() : v8::Persistent<T, M>() {}
++
++  template<typename S> inline Persistent(v8::Local<S> that) :
++      v8::Persistent<T, M>(v8::Isolate::GetCurrent(), that) {}
++
++  template<typename S, typename M2>
++  inline
++  Persistent(const v8::Persistent<S, M2> &that) :  // NOLINT(runtime/explicit)
++      v8::Persistent<T, M2>(v8::Isolate::GetCurrent(), that) {}
++
++  inline void Reset() { v8::PersistentBase<T>::Reset(); }
++
++  template <typename S>
++  inline void Reset(const v8::Local<S> &other) {
++    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
++  }
++
++  template <typename S>
++  inline void Reset(const v8::PersistentBase<S> &other) {
++    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
++  }
++
++  template<typename P>
++  inline void SetWeak(
++    P *parameter
++    , typename WeakCallbackInfo<P>::Callback callback
++    , WeakCallbackType type);
++
++ private:
++  inline T *operator*() const { return *PersistentBase<T>::persistent; }
++
++  template<typename S, typename M2>
++  inline void Copy(const Persistent<S, M2> &that) {
++    TYPE_CHECK(T, S);
++
++    this->Reset();
++
++    if (!that.IsEmpty()) {
++      this->Reset(that);
++      M::Copy(that, this);
++    }
++  }
++};
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++template<typename T>
++class Global : public v8::Global<T> {
++ public:
++  inline Global() : v8::Global<T>() {}
++
++  template<typename S> inline Global(v8::Local<S> that) :
++    v8::Global<T>(v8::Isolate::GetCurrent(), that) {}
++
++  template<typename S>
++  inline
++  Global(const v8::PersistentBase<S> &that) :  // NOLINT(runtime/explicit)
++      v8::Global<S>(v8::Isolate::GetCurrent(), that) {}
++
++  inline void Reset() { v8::PersistentBase<T>::Reset(); }
++
++  template <typename S>
++  inline void Reset(const v8::Local<S> &other) {
++    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
++  }
++
++  template <typename S>
++  inline void Reset(const v8::PersistentBase<S> &other) {
++    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
++  }
++
++  template<typename P>
++  inline void SetWeak(
++    P *parameter
++    , typename WeakCallbackInfo<P>::Callback callback
++    , WeakCallbackType type) {
++    reinterpret_cast<Persistent<T>*>(this)->SetWeak(
++        parameter, callback, type);
++  }
++};
++#else
++template<typename T>
++class Global : public v8::UniquePersistent<T> {
++ public:
++  inline Global() : v8::UniquePersistent<T>() {}
++
++  template<typename S> inline Global(v8::Local<S> that) :
++    v8::UniquePersistent<T>(v8::Isolate::GetCurrent(), that) {}
++
++  template<typename S>
++  inline
++  Global(const v8::PersistentBase<S> &that) :  // NOLINT(runtime/explicit)
++      v8::UniquePersistent<S>(v8::Isolate::GetCurrent(), that) {}
++
++  inline void Reset() { v8::PersistentBase<T>::Reset(); }
++
++  template <typename S>
++  inline void Reset(const v8::Local<S> &other) {
++    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
++  }
++
++  template <typename S>
++  inline void Reset(const v8::PersistentBase<S> &other) {
++    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
++  }
++
++  template<typename P>
++  inline void SetWeak(
++    P *parameter
++    , typename WeakCallbackInfo<P>::Callback callback
++    , WeakCallbackType type) {
++    reinterpret_cast<Persistent<T>*>(this)->SetWeak(
++        parameter, callback, type);
++  }
++};
++#endif
++
++#endif  // NAN_PERSISTENT_12_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4c9c59da70b66a8c2090cfefa9078fb886bcf646
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,242 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_PERSISTENT_PRE_12_INL_H_
++#define NAN_PERSISTENT_PRE_12_INL_H_
++
++template<typename T>
++class PersistentBase {
++  v8::Persistent<T> persistent;
++  template<typename U>
++  friend v8::Local<U> New(const PersistentBase<U> &p);
++  template<typename U, typename M>
++  friend v8::Local<U> New(const Persistent<U, M> &p);
++  template<typename U>
++  friend v8::Local<U> New(const Global<U> &p);
++  template<typename S> friend class ReturnValue;
++
++ public:
++  inline PersistentBase() :
++      persistent() {}
++
++  inline void Reset() {
++    persistent.Dispose();
++    persistent.Clear();
++  }
++
++  template<typename S>
++  inline void Reset(const v8::Local<S> &other) {
++    TYPE_CHECK(T, S);
++
++    if (!persistent.IsEmpty()) {
++      persistent.Dispose();
++    }
++
++    if (other.IsEmpty()) {
++      persistent.Clear();
++    } else {
++      persistent = v8::Persistent<T>::New(other);
++    }
++  }
++
++  template<typename S>
++  inline void Reset(const PersistentBase<S> &other) {
++    TYPE_CHECK(T, S);
++
++    if (!persistent.IsEmpty()) {
++      persistent.Dispose();
++    }
++
++    if (other.IsEmpty()) {
++      persistent.Clear();
++    } else {
++      persistent = v8::Persistent<T>::New(other.persistent);
++    }
++  }
++
++  inline bool IsEmpty() const { return persistent.IsEmpty(); }
++
++  inline void Empty() { persistent.Clear(); }
++
++  template<typename S>
++  inline bool operator==(const PersistentBase<S> &that) const {
++    return this->persistent == that.persistent;
++  }
++
++  template<typename S>
++  inline bool operator==(const v8::Local<S> &that) const {
++    return this->persistent == that;
++  }
++
++  template<typename S>
++  inline bool operator!=(const PersistentBase<S> &that) const {
++    return !operator==(that);
++  }
++
++  template<typename S>
++  inline bool operator!=(const v8::Local<S> &that) const {
++    return !operator==(that);
++  }
++
++  template<typename P>
++  inline void SetWeak(
++    P *parameter
++    , typename WeakCallbackInfo<P>::Callback callback
++    , WeakCallbackType type);
++
++  inline void ClearWeak() { persistent.ClearWeak(); }
++
++  inline void MarkIndependent() { persistent.MarkIndependent(); }
++
++  inline bool IsIndependent() const { return persistent.IsIndependent(); }
++
++  inline bool IsNearDeath() const { return persistent.IsNearDeath(); }
++
++  inline bool IsWeak() const { return persistent.IsWeak(); }
++
++ private:
++  inline explicit PersistentBase(v8::Persistent<T> that) :
++      persistent(that) { }
++  inline explicit PersistentBase(T *val) : persistent(val) {}
++  template<typename S, typename M> friend class Persistent;
++  template<typename S> friend class Global;
++  friend class ObjectWrap;
++};
++
++template<typename T>
++class NonCopyablePersistentTraits {
++ public:
++  typedef Persistent<T, NonCopyablePersistentTraits<T> >
++      NonCopyablePersistent;
++  static const bool kResetInDestructor = false;
++  template<typename S, typename M>
++  inline static void Copy(const Persistent<S, M> &source,
++                             NonCopyablePersistent *dest) {
++    Uncompilable<v8::Object>();
++  }
++
++  template<typename O> inline static void Uncompilable() {
++    TYPE_CHECK(O, v8::Primitive);
++  }
++};
++
++template<typename T>
++struct CopyablePersistentTraits {
++  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
++  static const bool kResetInDestructor = true;
++  template<typename S, typename M>
++  static inline void Copy(const Persistent<S, M> &source,
++                             CopyablePersistent *dest) {}
++};
++
++template<typename T, typename M> class Persistent :
++    public PersistentBase<T> {
++ public:
++  inline Persistent() {}
++
++  template<typename S> inline Persistent(v8::Handle<S> that)
++      : PersistentBase<T>(v8::Persistent<T>::New(that)) {
++    TYPE_CHECK(T, S);
++  }
++
++  inline Persistent(const Persistent &that) : PersistentBase<T>() {
++    Copy(that);
++  }
++
++  template<typename S, typename M2>
++  inline Persistent(const Persistent<S, M2> &that) :
++      PersistentBase<T>() {
++    Copy(that);
++  }
++
++  inline Persistent &operator=(const Persistent &that) {
++    Copy(that);
++    return *this;
++  }
++
++  template <class S, class M2>
++  inline Persistent &operator=(const Persistent<S, M2> &that) {
++    Copy(that);
++    return *this;
++  }
++
++  inline ~Persistent() {
++    if (M::kResetInDestructor) this->Reset();
++  }
++
++ private:
++  inline T *operator*() const { return *PersistentBase<T>::persistent; }
++
++  template<typename S, typename M2>
++  inline void Copy(const Persistent<S, M2> &that) {
++    TYPE_CHECK(T, S);
++
++    this->Reset();
++
++    if (!that.IsEmpty()) {
++      this->persistent = v8::Persistent<T>::New(that.persistent);
++      M::Copy(that, this);
++    }
++  }
++};
++
++template<typename T>
++class Global : public PersistentBase<T> {
++  struct RValue {
++    inline explicit RValue(Global* obj) : object(obj) {}
++    Global* object;
++  };
++
++ public:
++  inline Global() : PersistentBase<T>(0) { }
++
++  template <typename S>
++  inline Global(v8::Local<S> that)  // NOLINT(runtime/explicit)
++      : PersistentBase<T>(v8::Persistent<T>::New(that)) {
++    TYPE_CHECK(T, S);
++  }
++
++  template <typename S>
++  inline Global(const PersistentBase<S> &that)  // NOLINT(runtime/explicit)
++    : PersistentBase<T>(that) {
++    TYPE_CHECK(T, S);
++  }
++  /**
++   * Move constructor.
++   */
++  inline Global(RValue rvalue)  // NOLINT(runtime/explicit)
++    : PersistentBase<T>(rvalue.object->persistent) {
++    rvalue.object->Reset();
++  }
++  inline ~Global() { this->Reset(); }
++  /**
++   * Move via assignment.
++   */
++  template<typename S>
++  inline Global &operator=(Global<S> rhs) {
++    TYPE_CHECK(T, S);
++    this->Reset(rhs.persistent);
++    rhs.Reset();
++    return *this;
++  }
++  /**
++   * Cast operator for moves.
++   */
++  inline operator RValue() { return RValue(this); }
++  /**
++   * Pass allows returning uniques from functions, etc.
++   */
++  Global Pass() { return Global(RValue(this)); }
++
++ private:
++  Global(Global &);
++  void operator=(Global &);
++  template<typename S> friend class ReturnValue;
++};
++
++#endif  // NAN_PERSISTENT_PRE_12_INL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..15f44cc8c293861d46c73274e32b910f05011986
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,73 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_PRIVATE_H_
++#define NAN_PRIVATE_H_
++
++inline Maybe<bool>
++HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) {
++  HandleScope scope;
++#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::Local<v8::Context> context = isolate->GetCurrentContext();
++  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
++  return object->HasPrivate(context, private_key);
++#else
++  return Just(!object->GetHiddenValue(key).IsEmpty());
++#endif
++}
++
++inline MaybeLocal<v8::Value>
++GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) {
++#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::EscapableHandleScope scope(isolate);
++  v8::Local<v8::Context> context = isolate->GetCurrentContext();
++  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
++  v8::MaybeLocal<v8::Value> v = object->GetPrivate(context, private_key);
++  return scope.Escape(v.ToLocalChecked());
++#else
++  EscapableHandleScope scope;
++  v8::Local<v8::Value> v = object->GetHiddenValue(key);
++  if (v.IsEmpty()) {
++    v = Undefined();
++  }
++  return scope.Escape(v);
++#endif
++}
++
++inline Maybe<bool> SetPrivate(
++    v8::Local<v8::Object> object,
++    v8::Local<v8::String> key,
++    v8::Local<v8::Value> value) {
++#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
++  HandleScope scope;
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::Local<v8::Context> context = isolate->GetCurrentContext();
++  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
++  return object->SetPrivate(context, private_key, value);
++#else
++  return Just(object->SetHiddenValue(key, value));
++#endif
++}
++
++inline Maybe<bool> DeletePrivate(
++    v8::Local<v8::Object> object,
++    v8::Local<v8::String> key) {
++#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
++  HandleScope scope;
++  v8::Isolate *isolate = v8::Isolate::GetCurrent();
++  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
++  return object->DeletePrivate(isolate->GetCurrentContext(), private_key);
++#else
++  return Just(object->DeleteHiddenValue(key));
++#endif
++}
++
++#endif  // NAN_PRIVATE_H_
++
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a2e6437d12b74cd29fad17ed6c40e1e739eded2c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,305 @@@
++// Copyright Joyent, Inc. and other Node contributors.
++//
++// Permission is hereby granted, free of charge, to any person obtaining a
++// copy of this software and associated documentation files (the
++// "Software"), to deal in the Software without restriction, including
++// without limitation the rights to use, copy, modify, merge, publish,
++// distribute, sublicense, and/or sell copies of the Software, and to permit
++// persons to whom the Software is furnished to do so, subject to the
++// following conditions:
++//
++// The above copyright notice and this permission notice shall be included
++// in all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
++// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
++// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
++// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
++// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
++// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
++// USE OR OTHER DEALINGS IN THE SOFTWARE.
++
++#ifndef NAN_STRING_BYTES_H_
++#define NAN_STRING_BYTES_H_
++
++// Decodes a v8::Local<v8::String> or Buffer to a raw char*
++
++namespace imp {
++
++using v8::Local;
++using v8::Object;
++using v8::String;
++using v8::Value;
++
++
++//// Base 64 ////
++
++#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4)
++
++
++
++//// HEX ////
++
++static bool contains_non_ascii_slow(const char* buf, size_t len) {
++  for (size_t i = 0; i < len; ++i) {
++    if (buf[i] & 0x80) return true;
++  }
++  return false;
++}
++
++
++static bool contains_non_ascii(const char* src, size_t len) {
++  if (len < 16) {
++    return contains_non_ascii_slow(src, len);
++  }
++
++  const unsigned bytes_per_word = sizeof(void*);
++  const unsigned align_mask = bytes_per_word - 1;
++  const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
++
++  if (unaligned > 0) {
++    const unsigned n = bytes_per_word - unaligned;
++    if (contains_non_ascii_slow(src, n)) return true;
++    src += n;
++    len -= n;
++  }
++
++
++#if defined(__x86_64__) || defined(_WIN64)
++  const uintptr_t mask = 0x8080808080808080ll;
++#else
++  const uintptr_t mask = 0x80808080l;
++#endif
++
++  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
++
++  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
++    if (srcw[i] & mask) return true;
++  }
++
++  const unsigned remainder = len & align_mask;
++  if (remainder > 0) {
++    const size_t offset = len - remainder;
++    if (contains_non_ascii_slow(src + offset, remainder)) return true;
++  }
++
++  return false;
++}
++
++
++static void force_ascii_slow(const char* src, char* dst, size_t len) {
++  for (size_t i = 0; i < len; ++i) {
++    dst[i] = src[i] & 0x7f;
++  }
++}
++
++
++static void force_ascii(const char* src, char* dst, size_t len) {
++  if (len < 16) {
++    force_ascii_slow(src, dst, len);
++    return;
++  }
++
++  const unsigned bytes_per_word = sizeof(void*);
++  const unsigned align_mask = bytes_per_word - 1;
++  const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
++  const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
++
++  if (src_unalign > 0) {
++    if (src_unalign == dst_unalign) {
++      const unsigned unalign = bytes_per_word - src_unalign;
++      force_ascii_slow(src, dst, unalign);
++      src += unalign;
++      dst += unalign;
++      len -= src_unalign;
++    } else {
++      force_ascii_slow(src, dst, len);
++      return;
++    }
++  }
++
++#if defined(__x86_64__) || defined(_WIN64)
++  const uintptr_t mask = ~0x8080808080808080ll;
++#else
++  const uintptr_t mask = ~0x80808080l;
++#endif
++
++  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
++  uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
++
++  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
++    dstw[i] = srcw[i] & mask;
++  }
++
++  const unsigned remainder = len & align_mask;
++  if (remainder > 0) {
++    const size_t offset = len - remainder;
++    force_ascii_slow(src + offset, dst + offset, remainder);
++  }
++}
++
++
++static size_t base64_encode(const char* src,
++                            size_t slen,
++                            char* dst,
++                            size_t dlen) {
++  // We know how much we'll write, just make sure that there's space.
++  assert(dlen >= base64_encoded_size(slen) &&
++      "not enough space provided for base64 encode");
++
++  dlen = base64_encoded_size(slen);
++
++  unsigned a;
++  unsigned b;
++  unsigned c;
++  unsigned i;
++  unsigned k;
++  unsigned n;
++
++  static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
++                              "abcdefghijklmnopqrstuvwxyz"
++                              "0123456789+/";
++
++  i = 0;
++  k = 0;
++  n = slen / 3 * 3;
++
++  while (i < n) {
++    a = src[i + 0] & 0xff;
++    b = src[i + 1] & 0xff;
++    c = src[i + 2] & 0xff;
++
++    dst[k + 0] = table[a >> 2];
++    dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
++    dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)];
++    dst[k + 3] = table[c & 0x3f];
++
++    i += 3;
++    k += 4;
++  }
++
++  if (n != slen) {
++    switch (slen - n) {
++      case 1:
++        a = src[i + 0] & 0xff;
++        dst[k + 0] = table[a >> 2];
++        dst[k + 1] = table[(a & 3) << 4];
++        dst[k + 2] = '=';
++        dst[k + 3] = '=';
++        break;
++
++      case 2:
++        a = src[i + 0] & 0xff;
++        b = src[i + 1] & 0xff;
++        dst[k + 0] = table[a >> 2];
++        dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
++        dst[k + 2] = table[(b & 0x0f) << 2];
++        dst[k + 3] = '=';
++        break;
++    }
++  }
++
++  return dlen;
++}
++
++
++static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
++  // We know how much we'll write, just make sure that there's space.
++  assert(dlen >= slen * 2 &&
++      "not enough space provided for hex encode");
++
++  dlen = slen * 2;
++  for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
++    static const char hex[] = "0123456789abcdef";
++    uint8_t val = static_cast<uint8_t>(src[i]);
++    dst[k + 0] = hex[val >> 4];
++    dst[k + 1] = hex[val & 15];
++  }
++
++  return dlen;
++}
++
++
++
++static Local<Value> Encode(const char* buf,
++                           size_t buflen,
++                           enum Encoding encoding) {
++  assert(buflen <= node::Buffer::kMaxLength);
++  if (!buflen && encoding != BUFFER)
++    return New("").ToLocalChecked();
++
++  Local<String> val;
++  switch (encoding) {
++    case BUFFER:
++      return CopyBuffer(buf, buflen).ToLocalChecked();
++
++    case ASCII:
++      if (contains_non_ascii(buf, buflen)) {
++        char* out = new char[buflen];
++        force_ascii(buf, out, buflen);
++        val = New<String>(out, buflen).ToLocalChecked();
++        delete[] out;
++      } else {
++        val = New<String>(buf, buflen).ToLocalChecked();
++      }
++      break;
++
++    case UTF8:
++      val = New<String>(buf, buflen).ToLocalChecked();
++      break;
++
++    case BINARY: {
++      // TODO(isaacs) use ExternalTwoByteString?
++      const unsigned char *cbuf = reinterpret_cast<const unsigned char*>(buf);
++      uint16_t * twobytebuf = new uint16_t[buflen];
++      for (size_t i = 0; i < buflen; i++) {
++        // XXX is the following line platform independent?
++        twobytebuf[i] = cbuf[i];
++      }
++      val = New<String>(twobytebuf, buflen).ToLocalChecked();
++      delete[] twobytebuf;
++      break;
++    }
++
++    case BASE64: {
++      size_t dlen = base64_encoded_size(buflen);
++      char* dst = new char[dlen];
++
++      size_t written = base64_encode(buf, buflen, dst, dlen);
++      assert(written == dlen);
++
++      val = New<String>(dst, dlen).ToLocalChecked();
++      delete[] dst;
++      break;
++    }
++
++    case UCS2: {
++      const uint16_t* data = reinterpret_cast<const uint16_t*>(buf);
++      val = New<String>(data, buflen / 2).ToLocalChecked();
++      break;
++    }
++
++    case HEX: {
++      size_t dlen = buflen * 2;
++      char* dst = new char[dlen];
++      size_t written = hex_encode(buf, buflen, dst, dlen);
++      assert(written == dlen);
++
++      val = New<String>(dst, dlen).ToLocalChecked();
++      delete[] dst;
++      break;
++    }
++
++    default:
++      assert(0 && "unknown encoding");
++      break;
++  }
++
++  return val;
++}
++
++#undef base64_encoded_size
++
++}  // end of namespace imp
++
++#endif  // NAN_STRING_BYTES_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d28ae323e2276b43733be5cac407fd28b91e55c7
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,90 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_TYPEDARRAY_CONTENTS_H_
++#define NAN_TYPEDARRAY_CONTENTS_H_
++
++template<typename T>
++class TypedArrayContents {
++ public:
++  inline explicit TypedArrayContents(v8::Local<v8::Value> from) :
++      length_(0), data_(NULL) {
++    HandleScope scope;
++
++    size_t length = 0;
++    void*  data = NULL;
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++
++    if (from->IsArrayBufferView()) {
++      v8::Local<v8::ArrayBufferView> array =
++        v8::Local<v8::ArrayBufferView>::Cast(from);
++
++      const size_t    byte_length = array->ByteLength();
++      const ptrdiff_t byte_offset = array->ByteOffset();
++      v8::Local<v8::ArrayBuffer> buffer = array->Buffer();
++
++      length = byte_length / sizeof(T);
++      data   = static_cast<char*>(buffer->GetContents().Data()) + byte_offset;
++    }
++
++#else
++
++    if (from->IsObject() && !from->IsNull()) {
++      v8::Local<v8::Object> array = v8::Local<v8::Object>::Cast(from);
++
++      MaybeLocal<v8::Value> buffer = Get(array,
++        New<v8::String>("buffer").ToLocalChecked());
++      MaybeLocal<v8::Value> byte_length = Get(array,
++        New<v8::String>("byteLength").ToLocalChecked());
++      MaybeLocal<v8::Value> byte_offset = Get(array,
++        New<v8::String>("byteOffset").ToLocalChecked());
++
++      if (!buffer.IsEmpty() &&
++          !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() &&
++          !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) {
++        data = array->GetIndexedPropertiesExternalArrayData();
++        if(data) {
++          length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T);
++        }
++      }
++    }
++
++#endif
++
++#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L
++    assert(reinterpret_cast<uintptr_t>(data) % alignof (T) == 0);
++#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__)
++    assert(reinterpret_cast<uintptr_t>(data) % __alignof(T) == 0);
++#else
++    assert(reinterpret_cast<uintptr_t>(data) % sizeof (T) == 0);
++#endif
++
++    length_ = length;
++    data_   = static_cast<T*>(data);
++  }
++
++  inline size_t length() const      { return length_; }
++  inline T* operator*()             { return data_;   }
++  inline const T* operator*() const { return data_;   }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents)
++
++  //Disable heap allocation
++  void *operator new(size_t size);
++  void operator delete(void *, size_t) {
++    abort();
++  }
++
++  size_t  length_;
++  T*      data_;
++};
++
++#endif  // NAN_TYPEDARRAY_CONTENTS_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7e7ab07b8512dbbcc1f09c498e221032d2cd345f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,437 @@@
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++#ifndef NAN_WEAK_H_
++#define NAN_WEAK_H_
++
++static const int kInternalFieldsInWeakCallback = 2;
++static const int kNoInternalFieldIndex = -1;
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
++    v8::WeakCallbackInfo<WeakCallbackInfo<T> > const&
++# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
++    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
++#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION
++# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
++    v8::PhantomCallbackData<WeakCallbackInfo<T> > const&
++# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
++    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
++#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
++    v8::PhantomCallbackData<WeakCallbackInfo<T> > const&
++# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
++    v8::InternalFieldsCallbackData<WeakCallbackInfo<T>, void> const&
++# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++# define NAN_WEAK_CALLBACK_DATA_TYPE_ \
++    v8::WeakCallbackData<S, WeakCallbackInfo<T> > const&
++# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_
++#else
++# define NAN_WEAK_CALLBACK_DATA_TYPE_ void *
++# define NAN_WEAK_CALLBACK_SIG_ \
++    v8::Persistent<v8::Value>, NAN_WEAK_CALLBACK_DATA_TYPE_
++#endif
++
++template<typename T>
++class WeakCallbackInfo {
++ public:
++  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
++  WeakCallbackInfo(
++      Persistent<v8::Value> *persistent
++    , Callback callback
++    , void *parameter
++    , void *field1 = 0
++    , void *field2 = 0) :
++        callback_(callback), isolate_(0), parameter_(parameter) {
++    std::memcpy(&persistent_, persistent, sizeof (v8::Persistent<v8::Value>));
++    internal_fields_[0] = field1;
++    internal_fields_[1] = field2;
++  }
++  inline v8::Isolate *GetIsolate() const { return isolate_; }
++  inline T *GetParameter() const { return static_cast<T*>(parameter_); }
++  inline void *GetInternalField(int index) const {
++    assert((index == 0 || index == 1) && "internal field index out of bounds");
++    if (index == 0) {
++      return internal_fields_[0];
++    } else {
++      return internal_fields_[1];
++    }
++  }
++
++ private:
++  NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo)
++  Callback callback_;
++  v8::Isolate *isolate_;
++  void *parameter_;
++  void *internal_fields_[kInternalFieldsInWeakCallback];
++  v8::Persistent<v8::Value> persistent_;
++  template<typename S, typename M> friend class Persistent;
++  template<typename S> friend class PersistentBase;
++#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION
++# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++  template<typename S>
++  static void invoke(NAN_WEAK_CALLBACK_SIG_ data);
++  template<typename S>
++  static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data);
++# else
++  static void invoke(NAN_WEAK_CALLBACK_SIG_ data);
++  static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data);
++# endif
++#else
++# if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                     \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++  template<bool isFirstPass>
++  static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data);
++  template<bool isFirstPass>
++  static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data);
++# else
++  static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data);
++  static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data);
++# endif
++  static WeakCallbackInfo *unwrapparameter(
++      NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data);
++  static WeakCallbackInfo *unwraptwofield(
++      NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data);
++#endif
++};
++
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++
++template<typename T>
++template<bool isFirstPass>
++void
++WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) {
++  WeakCallbackInfo<T> *cbinfo = unwrapparameter(data);
++  if (isFirstPass) {
++    cbinfo->persistent_.Reset();
++    data.SetSecondPassCallback(invokeparameter<false>);
++  } else {
++    cbinfo->callback_(*cbinfo);
++    delete cbinfo;
++  }
++}
++
++template<typename T>
++template<bool isFirstPass>
++void
++WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) {
++  WeakCallbackInfo<T> *cbinfo = unwraptwofield(data);
++  if (isFirstPass) {
++    cbinfo->persistent_.Reset();
++    data.SetSecondPassCallback(invoketwofield<false>);
++  } else {
++    cbinfo->callback_(*cbinfo);
++    delete cbinfo;
++  }
++}
++
++template<typename T>
++WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter(
++    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) {
++  WeakCallbackInfo<T> *cbinfo =
++      static_cast<WeakCallbackInfo<T>*>(data.GetParameter());
++  cbinfo->isolate_ = data.GetIsolate();
++  return cbinfo;
++}
++
++template<typename T>
++WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield(
++    NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) {
++  WeakCallbackInfo<T> *cbinfo =
++      static_cast<WeakCallbackInfo<T>*>(data.GetInternalField(0));
++  cbinfo->isolate_ = data.GetIsolate();
++  return cbinfo;
++}
++
++#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_
++#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_
++#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
++# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++
++template<typename T>
++void
++WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) {
++  WeakCallbackInfo<T> *cbinfo = unwrapparameter(data);
++  cbinfo->persistent_.Reset();
++  cbinfo->callback_(*cbinfo);
++  delete cbinfo;
++}
++
++template<typename T>
++void
++WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) {
++  WeakCallbackInfo<T> *cbinfo = unwraptwofield(data);
++  cbinfo->persistent_.Reset();
++  cbinfo->callback_(*cbinfo);
++  delete cbinfo;
++}
++
++template<typename T>
++WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter(
++    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) {
++  WeakCallbackInfo<T> *cbinfo =
++       static_cast<WeakCallbackInfo<T>*>(data.GetParameter());
++  cbinfo->isolate_ = data.GetIsolate();
++  return cbinfo;
++}
++
++template<typename T>
++WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield(
++    NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) {
++  WeakCallbackInfo<T> *cbinfo =
++       static_cast<WeakCallbackInfo<T>*>(data.GetInternalField1());
++  cbinfo->isolate_ = data.GetIsolate();
++  return cbinfo;
++}
++
++#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_
++#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_
++#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
++#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++
++template<typename T>
++template<typename S>
++void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) {
++  WeakCallbackInfo<T> *cbinfo = unwrap(data);
++  cbinfo->persistent_.Reset();
++  cbinfo->callback_(*cbinfo);
++  delete cbinfo;
++}
++
++template<typename T>
++template<typename S>
++WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap(
++    NAN_WEAK_CALLBACK_DATA_TYPE_ data) {
++  void *parameter = data.GetParameter();
++  WeakCallbackInfo<T> *cbinfo =
++      static_cast<WeakCallbackInfo<T>*>(parameter);
++  cbinfo->isolate_ = data.GetIsolate();
++  return cbinfo;
++}
++
++#undef NAN_WEAK_CALLBACK_SIG_
++#undef NAN_WEAK_CALLBACK_DATA_TYPE_
++#else
++
++template<typename T>
++void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) {
++  WeakCallbackInfo<T> *cbinfo = unwrap(data);
++  cbinfo->persistent_.Dispose();
++  cbinfo->persistent_.Clear();
++  cbinfo->callback_(*cbinfo);
++  delete cbinfo;
++}
++
++template<typename T>
++WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap(
++    NAN_WEAK_CALLBACK_DATA_TYPE_ data) {
++  WeakCallbackInfo<T> *cbinfo =
++      static_cast<WeakCallbackInfo<T>*>(data);
++  cbinfo->isolate_ = v8::Isolate::GetCurrent();
++  return cbinfo;
++}
++
++#undef NAN_WEAK_CALLBACK_SIG_
++#undef NAN_WEAK_CALLBACK_DATA_TYPE_
++#endif
++
++#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
++  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
++template<typename T, typename M>
++template<typename P>
++inline void Persistent<T, M>::SetWeak(
++    P *parameter
++  , typename WeakCallbackInfo<P>::Callback callback
++  , WeakCallbackType type) {
++  WeakCallbackInfo<P> *wcbd;
++  if (type == WeakCallbackType::kParameter) {
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , parameter);
++    v8::PersistentBase<T>::SetWeak(
++        wcbd
++      , WeakCallbackInfo<P>::template invokeparameter<true>
++      , type);
++  } else {
++    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
++    assert((*self_v)->IsObject());
++    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
++    int count = self->InternalFieldCount();
++    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
++    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
++      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
++    }
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , 0
++      , internal_fields[0]
++      , internal_fields[1]);
++    self->SetAlignedPointerInInternalField(0, wcbd);
++    v8::PersistentBase<T>::SetWeak(
++        static_cast<WeakCallbackInfo<P>*>(0)
++      , WeakCallbackInfo<P>::template invoketwofield<true>
++      , type);
++  }
++}
++#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION
++template<typename T, typename M>
++template<typename P>
++inline void Persistent<T, M>::SetWeak(
++    P *parameter
++  , typename WeakCallbackInfo<P>::Callback callback
++  , WeakCallbackType type) {
++  WeakCallbackInfo<P> *wcbd;
++  if (type == WeakCallbackType::kParameter) {
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , parameter);
++    v8::PersistentBase<T>::SetPhantom(
++        wcbd
++      , WeakCallbackInfo<P>::invokeparameter);
++  } else {
++    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
++    assert((*self_v)->IsObject());
++    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
++    int count = self->InternalFieldCount();
++    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
++    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
++      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
++    }
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , 0
++      , internal_fields[0]
++      , internal_fields[1]);
++    self->SetAlignedPointerInInternalField(0, wcbd);
++    v8::PersistentBase<T>::SetPhantom(
++        static_cast<WeakCallbackInfo<P>*>(0)
++      , WeakCallbackInfo<P>::invoketwofield
++      , 0
++      , count > 1 ? 1 : kNoInternalFieldIndex);
++  }
++}
++#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
++template<typename T, typename M>
++template<typename P>
++inline void Persistent<T, M>::SetWeak(
++    P *parameter
++  , typename WeakCallbackInfo<P>::Callback callback
++  , WeakCallbackType type) {
++  WeakCallbackInfo<P> *wcbd;
++  if (type == WeakCallbackType::kParameter) {
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , parameter);
++    v8::PersistentBase<T>::SetPhantom(
++        wcbd
++      , WeakCallbackInfo<P>::invokeparameter);
++  } else {
++    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
++    assert((*self_v)->IsObject());
++    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
++    int count = self->InternalFieldCount();
++    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
++    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
++      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
++    }
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , 0
++      , internal_fields[0]
++      , internal_fields[1]);
++    self->SetAlignedPointerInInternalField(0, wcbd);
++    v8::PersistentBase<T>::SetPhantom(
++        WeakCallbackInfo<P>::invoketwofield
++      , 0
++      , count > 1 ? 1 : kNoInternalFieldIndex);
++  }
++}
++#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
++template<typename T, typename M>
++template<typename P>
++inline void Persistent<T, M>::SetWeak(
++    P *parameter
++  , typename WeakCallbackInfo<P>::Callback callback
++  , WeakCallbackType type) {
++  WeakCallbackInfo<P> *wcbd;
++  if (type == WeakCallbackType::kParameter) {
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , parameter);
++    v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke);
++  } else {
++    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
++    assert((*self_v)->IsObject());
++    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
++    int count = self->InternalFieldCount();
++    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
++    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
++      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
++    }
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , 0
++      , internal_fields[0]
++      , internal_fields[1]);
++    v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke);
++  }
++}
++#else
++template<typename T>
++template<typename P>
++inline void PersistentBase<T>::SetWeak(
++    P *parameter
++  , typename WeakCallbackInfo<P>::Callback callback
++  , WeakCallbackType type) {
++  WeakCallbackInfo<P> *wcbd;
++  if (type == WeakCallbackType::kParameter) {
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , parameter);
++    persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke);
++  } else {
++    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
++    assert((*self_v)->IsObject());
++    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
++    int count = self->InternalFieldCount();
++    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
++    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
++      internal_fields[i] = self->GetPointerFromInternalField(i);
++    }
++    wcbd = new WeakCallbackInfo<P>(
++        reinterpret_cast<Persistent<v8::Value>*>(this)
++      , callback
++      , 0
++      , internal_fields[0]
++      , internal_fields[1]);
++    persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke);
++  }
++}
++#endif
++
++#endif  // NAN_WEAK_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..302da5ec743319c2c784a263221d3bfd917ee0f2
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,109 @@@
++{
++  "name": "nan",
++  "version": "2.14.0",
++  "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 11 compatibility",
++  "main": "include_dirs.js",
++  "repository": {
++    "type": "git",
++    "url": "git://github.com/nodejs/nan.git"
++  },
++  "scripts": {
++    "test": "tap --gc --stderr test/js/*-test.js",
++    "test:worker": "node --experimental-worker test/tap-as-worker.js --gc --stderr test/js/*-test.js",
++    "rebuild-tests": "node-gyp rebuild --msvs_version=2015 --directory test",
++    "docs": "doc/.build.sh"
++  },
++  "contributors": [
++    {
++      "name": "Rod Vagg",
++      "email": "r@va.gg",
++      "url": "https://github.com/rvagg"
++    },
++    {
++      "name": "Benjamin Byholm",
++      "email": "bbyholm@abo.fi",
++      "url": "https://github.com/kkoopa/"
++    },
++    {
++      "name": "Trevor Norris",
++      "email": "trev.norris@gmail.com",
++      "url": "https://github.com/trevnorris"
++    },
++    {
++      "name": "Nathan Rajlich",
++      "email": "nathan@tootallnate.net",
++      "url": "https://github.com/TooTallNate"
++    },
++    {
++      "name": "Brett Lawson",
++      "email": "brett19@gmail.com",
++      "url": "https://github.com/brett19"
++    },
++    {
++      "name": "Ben Noordhuis",
++      "email": "info@bnoordhuis.nl",
++      "url": "https://github.com/bnoordhuis"
++    },
++    {
++      "name": "David Siegel",
++      "email": "david@artcom.de",
++      "url": "https://github.com/agnat"
++    },
++    {
++      "name": "Michael Ira Krufky",
++      "email": "mkrufky@gmail.com",
++      "url": "https://github.com/mkrufky"
++    }
++  ],
++  "devDependencies": {
++    "bindings": "~1.2.1",
++    "commander": "^2.8.1",
++    "glob": "^5.0.14",
++    "request": "=2.81.0",
++    "node-gyp": "~3.6.2",
++    "readable-stream": "^2.1.4",
++    "tap": "~0.7.1",
++    "xtend": "~4.0.0"
++  },
++  "license": "MIT",
++  "gitHead": "1dcc61bd06d84e389bfd5311b2b1492a14c74201",
++  "bugs": {
++    "url": "https://github.com/nodejs/nan/issues"
++  },
++  "homepage": "https://github.com/nodejs/nan#readme",
++  "_id": "nan@2.14.0",
++  "_npmVersion": "5.6.0",
++  "_nodeVersion": "9.6.0",
++  "_npmUser": {
++    "name": "kkoopa",
++    "email": "bbyholm@abo.fi"
++  },
++  "dist": {
++    "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==",
++    "shasum": "7818f722027b2459a86f0295d434d1fc2336c52c",
++    "tarball": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz",
++    "fileCount": 46,
++    "unpackedSize": 417060,
++    "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc3bXpCRA9TVsSAnZWagAApycP/2mhtcraLrh5RRziC2xM\nUKDaEjBIznHn7PqDWecW3HW/CGrUfmuxpDCBlE2fBm2cxF26nB/CV6xoD2W1\nkyu4MkRcKiAvNW0h4a5sTwXey0U6xc8JRBhBTWgfiY2aQoA4fIO5akmbIa/w\nyT6tspFQ0BQWKBrxlSOqfQ/lARU4Dzy2eiKu1aWMffQecgqOPTrlb5/QxFsr\nUmfdePyO2odVrjDiiNJsfkHeMh66ED4n7szrRjwkz7FTkoEF0dMOw/bWJU2X\nEYVziHG7rm9B4Blzv6KtqG4Y9Gty8epOG+itSLQcc088H86TXYXJn6y75+lf\n1Lw5E9lxw5XLfVnE7uzr0NVHhcj/M3RaGzXySi7v2AWMbF6wqxtAdebdNaew\nIpc3+NVj2OjA/79bzzhU76MG0PrYURE8UmVugHZHGp9L1PraD/jWqCT1JMGE\n1qGu2dSlsqoyNe9Y1pTs/kc+I4KLjwDqo14NyQQk8quvkyHrQ66oO5lAPN4U\n5ms7vR+FOZYrtX7jQDTAs9N169N0IxhGwgsUH4zRza2RkkdTzsjyEnPhqlrI\n6tIrfYldrudrGtcNmLJqY7fTUA86L3f7SQvlnpfsDPUFagfwQr4Uz9JE8q1k\nhbe8CqTuhbET2AZNFlBxf0ii3ipwNXXJtB/0hIVQCfud1vbdS1IuOibc2/YY\n6ep0\r\n=AZxH\r\n-----END PGP SIGNATURE-----\r\n"
++  },
++  "maintainers": [
++    {
++      "name": "kkoopa",
++      "email": "bbyholm@abo.fi"
++    },
++    {
++      "name": "rvagg",
++      "email": "rod@vagg.org"
++    }
++  ],
++  "directories": {},
++  "_npmOperationalInternal": {
++    "host": "s3://npm-registry-packages",
++    "tmp": "tmp/nan_2.14.0_1558033896058_0.6879275796293267"
++  },
++  "_hasShrinkwrap": false,
++  "_shasum": "7818f722027b2459a86f0295d434d1fc2336c52c",
++  "_from": "nan@^2.14.0",
++  "_resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz",
++  "readme": "ERROR: No README data found!"
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..337f8bf2c2bed35071f44064780364d66208d5d3
new file mode 100755 (executable)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,412 @@@
++#!/usr/bin/env node
++/*********************************************************************
++ * NAN - Native Abstractions for Node.js
++ *
++ * Copyright (c) 2018 NAN contributors
++ *
++ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
++ ********************************************************************/
++
++var commander = require('commander'),
++    fs = require('fs'),
++    glob = require('glob'),
++    groups = [],
++    total = 0,
++    warning1 = '/* ERROR: Rewrite using Buffer */\n',
++    warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n',
++    length,
++    i;
++
++fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) {
++  if (err) {
++    throw err;
++  }
++
++  commander
++      .version(JSON.parse(data).version)
++      .usage('[options] <file ...>')
++      .parse(process.argv);
++
++  if (!process.argv.slice(2).length) {
++    commander.outputHelp();
++  }
++});
++
++/* construct strings representing regular expressions
++   each expression contains a unique group allowing for identification of the match
++   the index of this key group, relative to the regular expression in question,
++    is indicated by the first array member */
++
++/* simple substistutions, key group is the entire match, 0 */
++groups.push([0, [
++  '_NAN_',
++  'NODE_SET_METHOD',
++  'NODE_SET_PROTOTYPE_METHOD',
++  'NanAsciiString',
++  'NanEscapeScope',
++  'NanReturnValue',
++  'NanUcs2String'].join('|')]);
++
++/* substitutions of parameterless macros, key group is 1 */
++groups.push([1, ['(', [
++  'NanEscapableScope',
++  'NanReturnNull',
++  'NanReturnUndefined',
++  'NanScope'].join('|'), ')\\(\\)'].join('')]);
++
++/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */
++groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']);
++
++/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ 
++groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]);
++
++/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */
++groups.push([2, ['(', warning2, ')?', '^.*?(', [
++      'GetIndexedPropertiesExternalArrayDataLength',
++      'GetIndexedPropertiesExternalArrayData',
++      'GetIndexedPropertiesExternalArrayDataType',
++      'GetIndexedPropertiesPixelData',
++      'GetIndexedPropertiesPixelDataLength',
++      'HasIndexedPropertiesInExternalArrayData',
++      'HasIndexedPropertiesInPixelData',
++      'SetIndexedPropertiesToExternalArrayData',
++      'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]);
++
++/* No need for NanScope in V8-exposed methods, key group 2 */
++groups.push([2, ['((', [
++      'NAN_METHOD',
++      'NAN_GETTER',
++      'NAN_SETTER',
++      'NAN_PROPERTY_GETTER',
++      'NAN_PROPERTY_SETTER',
++      'NAN_PROPERTY_ENUMERATOR',
++      'NAN_PROPERTY_DELETER',
++      'NAN_PROPERTY_QUERY',
++      'NAN_INDEX_GETTER',
++      'NAN_INDEX_SETTER',
++      'NAN_INDEX_ENUMERATOR',
++      'NAN_INDEX_DELETER',
++      'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]);
++
++/* v8::Value::ToXXXXXXX returns v8::MaybeLocal<T>, key group 3 */
++groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [
++      'Boolean',
++      'Number',
++      'String',
++      'Object',
++      'Integer',
++      'Uint32',
++      'Int32'].join('|'), ')\\('].join('')]);
++
++/* v8::Value::XXXXXXXValue returns v8::Maybe<T>, key group 3 */
++groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [
++      'Boolean',
++      'Number',
++      'Integer',
++      'Uint32',
++      'Int32'].join('|'), ')Value)\\('].join('')]);
++
++/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */
++groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']);
++
++/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */
++groups.push([1, ['(', [
++  'NanDisposePersistent',
++  'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]);
++
++/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */
++groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']);
++
++/* Many methods of v8::Object and others now return v8::MaybeLocal<T>, key group 3 */
++groups.push([3, ['([\\s])([^\\s]+)->(', [
++  'GetEndColumn',
++  'GetFunction',
++  'GetLineNumber',
++  'NewInstance',
++  'GetPropertyNames',
++  'GetOwnPropertyNames',
++  'GetSourceLine',
++  'GetStartColumn',
++  'ObjectProtoToString',
++  'ToArrayIndex',
++  'ToDetailString',
++  'CallAsConstructor',
++  'CallAsFunction',
++  'CloneElementAt',
++  'Delete',
++  'ForceSet',
++  'Get',
++  'GetPropertyAttributes',
++  'GetRealNamedProperty',
++  'GetRealNamedPropertyInPrototypeChain',
++  'Has',
++  'HasOwnProperty',
++  'HasRealIndexedProperty',
++  'HasRealNamedCallbackProperty',
++  'HasRealNamedProperty',
++  'Set',
++  'SetAccessor',
++  'SetIndexedPropertyHandler',
++  'SetNamedPropertyHandler',
++  'SetPrototype'].join('|'), ')\\('].join('')]);
++
++/* You should get an error if any of these fail anyways,
++   or handle the error better, it is indicated either way, key group 2 */
++groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]);
++
++/* v8::Value::Equals now returns a v8::Maybe, key group 3 */
++groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']);
++
++/* NanPersistent makes this unnecessary, key group 1 */
++groups.push([1, '(NanAssignPersistent)(?:<v8\\:\\:[^>]+>)?\\(([^,]+),\\s*']);
++
++/* args has been renamed to info, key group 2 */
++groups.push([2, '(\\W)(args)(\\W)'])
++
++/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */
++groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']);
++
++/* v8::Persistent was replaced with NanPersistent, key group 2 */
++groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']);
++
++/* counts the number of capturing groups in a well-formed regular expression,
++   ignoring non-capturing groups and escaped parentheses */
++function groupcount(s) {
++  var positive = s.match(/\((?!\?)/g),
++      negative = s.match(/\\\(/g);
++  return (positive ? positive.length : 0) - (negative ? negative.length : 0);
++}
++
++/* compute the absolute position of each key group in the joined master RegExp */
++for (i = 1, length = groups.length; i < length; i++) {
++      total += groupcount(groups[i - 1][1]);
++      groups[i][0] += total;
++}
++
++/* create the master RegExp, whis is the union of all the groups' expressions */
++master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm');
++
++/* replacement function for String.replace, receives 21 arguments */
++function replace() {
++      /* simple expressions */
++      switch (arguments[groups[0][0]]) {
++        case '_NAN_':
++          return 'NAN_';
++        case 'NODE_SET_METHOD':
++          return 'NanSetMethod';
++        case 'NODE_SET_PROTOTYPE_METHOD':
++          return 'NanSetPrototypeMethod';
++        case 'NanAsciiString':
++          return 'NanUtf8String';
++        case 'NanEscapeScope':
++          return 'scope.Escape';
++        case 'NanReturnNull':
++          return 'info.GetReturnValue().SetNull';
++        case 'NanReturnValue':
++          return 'info.GetReturnValue().Set';
++        case 'NanUcs2String':
++          return 'v8::String::Value';
++        default:
++      }
++
++      /* macros without arguments */
++      switch (arguments[groups[1][0]]) {
++        case 'NanEscapableScope':
++          return 'NanEscapableScope scope'
++        case 'NanReturnUndefined':
++          return 'return';
++        case 'NanScope':
++          return 'NanScope scope';
++        default:
++      }
++
++      /* TryCatch, emulate negative backref */
++      if (arguments[groups[2][0]] === 'TryCatch') {
++        return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch';
++      }
++
++      /* NanNew("foo") --> NanNew("foo").ToLocalChecked() */
++      if (arguments[groups[3][0]] === 'NanNew') {
++        return [arguments[0], '.ToLocalChecked()'].join('');
++      }
++
++      /* insert warning for removed functions as comment on new line above */
++      switch (arguments[groups[4][0]]) {
++        case 'GetIndexedPropertiesExternalArrayData':
++        case 'GetIndexedPropertiesExternalArrayDataLength':
++        case 'GetIndexedPropertiesExternalArrayDataType':
++        case 'GetIndexedPropertiesPixelData':
++        case 'GetIndexedPropertiesPixelDataLength':
++        case 'HasIndexedPropertiesInExternalArrayData':
++        case 'HasIndexedPropertiesInPixelData':
++        case 'SetIndexedPropertiesToExternalArrayData':
++        case 'SetIndexedPropertiesToPixelData':
++          return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join('');
++        default:
++      }
++
++     /* remove unnecessary NanScope() */
++      switch (arguments[groups[5][0]]) {
++        case 'NAN_GETTER':
++        case 'NAN_METHOD':
++        case 'NAN_SETTER':
++        case 'NAN_INDEX_DELETER':
++        case 'NAN_INDEX_ENUMERATOR':
++        case 'NAN_INDEX_GETTER':
++        case 'NAN_INDEX_QUERY':
++        case 'NAN_INDEX_SETTER':
++        case 'NAN_PROPERTY_DELETER':
++        case 'NAN_PROPERTY_ENUMERATOR':
++        case 'NAN_PROPERTY_GETTER':
++        case 'NAN_PROPERTY_QUERY':
++        case 'NAN_PROPERTY_SETTER':
++          return arguments[groups[5][0] - 1];
++        default:
++      }
++
++      /* Value converstion */
++      switch (arguments[groups[6][0]]) {
++        case 'Boolean':
++        case 'Int32':
++        case 'Integer':
++        case 'Number':
++        case 'Object':
++        case 'String':
++        case 'Uint32':
++          return [arguments[groups[6][0] - 2], 'NanTo<v8::', arguments[groups[6][0]], '>(',  arguments[groups[6][0] - 1]].join('');
++        default:
++      }
++
++      /* other value conversion */
++      switch (arguments[groups[7][0]]) {
++        case 'BooleanValue':
++          return [arguments[groups[7][0] - 2], 'NanTo<bool>(', arguments[groups[7][0] - 1]].join('');
++        case 'Int32Value':
++          return [arguments[groups[7][0] - 2], 'NanTo<int32_t>(', arguments[groups[7][0] - 1]].join('');
++        case 'IntegerValue':
++          return [arguments[groups[7][0] - 2], 'NanTo<int64_t>(', arguments[groups[7][0] - 1]].join('');
++        case 'Uint32Value':
++          return [arguments[groups[7][0] - 2], 'NanTo<uint32_t>(', arguments[groups[7][0] - 1]].join('');
++        default:
++      }
++
++      /* NAN_WEAK_CALLBACK */
++      if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') {
++        return ['template<typename T>\nvoid ',
++          arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo<T> &data)'].join('');
++      }
++
++      /* use methods on NAN classes instead */
++      switch (arguments[groups[9][0]]) {
++        case 'NanDisposePersistent':
++          return [arguments[groups[9][0] + 1], '.Reset('].join('');
++        case 'NanObjectWrapHandle':
++          return [arguments[groups[9][0] + 1], '->handle('].join('');
++        default:
++      }
++
++      /* use method on NanPersistent instead */
++      if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') {
++        return arguments[groups[10][0] + 1] + '.SetWeak(';
++      }
++
++      /* These return Maybes, the upper ones take no arguments */
++      switch (arguments[groups[11][0]]) {
++        case 'GetEndColumn':
++        case 'GetFunction':
++        case 'GetLineNumber':
++        case 'GetOwnPropertyNames':
++        case 'GetPropertyNames':
++        case 'GetSourceLine':
++        case 'GetStartColumn':
++        case 'NewInstance':
++        case 'ObjectProtoToString':
++        case 'ToArrayIndex':
++        case 'ToDetailString':
++          return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join('');
++        case 'CallAsConstructor':
++        case 'CallAsFunction':
++        case 'CloneElementAt':
++        case 'Delete':
++        case 'ForceSet':
++        case 'Get':
++        case 'GetPropertyAttributes':
++        case 'GetRealNamedProperty':
++        case 'GetRealNamedPropertyInPrototypeChain':
++        case 'Has':
++        case 'HasOwnProperty':
++        case 'HasRealIndexedProperty':
++        case 'HasRealNamedCallbackProperty':
++        case 'HasRealNamedProperty':
++        case 'Set':
++        case 'SetAccessor':
++        case 'SetIndexedPropertyHandler':
++        case 'SetNamedPropertyHandler':
++        case 'SetPrototype':
++          return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join('');
++        default:
++      }
++
++      /* Automatic ToLocalChecked(), take it or leave it */
++      switch (arguments[groups[12][0]]) {
++        case 'Date':
++        case 'String':
++        case 'RegExp':
++          return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join('');
++        default:
++      }
++
++      /* NanEquals is now required for uniformity */
++      if (arguments[groups[13][0]] === 'Equals') {
++        return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join('');
++      }
++
++      /* use method on replacement class instead */
++      if (arguments[groups[14][0]] === 'NanAssignPersistent') {
++        return [arguments[groups[14][0] + 1], '.Reset('].join('');
++      }
++
++      /* args --> info */
++      if (arguments[groups[15][0]] === 'args') {
++        return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join('');
++      }
++
++      /* ObjectWrap --> NanObjectWrap */
++      if (arguments[groups[16][0]] === 'ObjectWrap') {
++        return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join('');
++      }
++
++      /* Persistent --> NanPersistent */
++      if (arguments[groups[17][0]] === 'Persistent') {
++        return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join('');
++      }
++
++      /* This should not happen. A switch is probably missing a case if it does. */
++      throw 'Unhandled match: ' + arguments[0];
++}
++
++/* reads a file, runs replacement and writes it back */
++function processFile(file) {
++  fs.readFile(file, {encoding: 'utf8'}, function (err, data) {
++    if (err) {
++      throw err;
++    }
++
++    /* run replacement twice, might need more runs */
++    fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) {
++      if (err) {
++        throw err;
++      }
++    });
++  });
++}
++
++/* process file names from command line and process the identified files */
++for (i = 2, length = process.argv.length; i < length; i++) {
++  glob(process.argv[i], function (err, matches) {
++    if (err) {
++      throw err;
++    }
++    matches.forEach(processFile);
++  });
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..7f07e4b8256dd136943943b575776971c36c25e3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,14 @@@
++1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions,
++false positives and missed opportunities. The input files are rewritten in place. Make sure that
++you have backups. You will have to manually review the changes afterwards and do some touchups.
++
++```sh
++$ tools/1to2.js
++
++  Usage: 1to2 [options] <file ...>
++
++  Options:
++
++    -h, --help     output usage information
++    -V, --version  output the version number
++```
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2dcdd789394965b8150ff96ead49f1a6ac9caf6a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,19 @@@
++{
++  "name": "1to2",
++  "version": "1.0.0",
++  "description": "NAN 1 -> 2 Migration Script",
++  "main": "1to2.js",
++  "repository": {
++    "type": "git",
++    "url": "git://github.com/nodejs/nan.git"
++  },
++  "contributors": [
++    "Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)",
++    "Mathias Küsel (https://github.com/mathiask88/)"
++  ],
++  "dependencies": {
++    "glob": "~5.0.10",
++    "commander": "~2.8.1"
++  },
++  "license": "MIT"
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..82fae375ca82f87962a5e6638556e9150298bcae
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,89 @@@
++{
++  "name": "node-pty",
++  "description": "Fork pseudoterminals in Node.JS",
++  "author": {
++    "name": "Microsoft Corporation"
++  },
++  "version": "0.9.0",
++  "license": "MIT",
++  "main": "./lib/index.js",
++  "types": "./typings/node-pty.d.ts",
++  "repository": {
++    "type": "git",
++    "url": "git://github.com/Tyriar/node-pty.git"
++  },
++  "homepage": "https://github.com/Tyriar/node-pty",
++  "bugs": {
++    "url": "https://github.com/Tyriar/node-pty/issues"
++  },
++  "keywords": [
++    "pty",
++    "tty",
++    "terminal",
++    "pseudoterminal",
++    "forkpty",
++    "openpty"
++  ],
++  "scripts": {
++    "tsc": "tsc",
++    "watch": "tsc -w",
++    "lint": "tslint 'src/**/*.ts'",
++    "install": "node scripts/install.js",
++    "postinstall": "node scripts/post-install.js",
++    "test": "cross-env NODE_ENV=test mocha -R spec --exit lib/*.test.js",
++    "prepare": "npm run tsc",
++    "prepublishOnly": "npm run tsc"
++  },
++  "dependencies": {
++    "nan": "^2.14.0"
++  },
++  "devDependencies": {
++    "@types/mocha": "^5.0.0",
++    "@types/node": "8",
++    "cross-env": "^5.1.4",
++    "mocha": "^5.0.5",
++    "ps-list": "^6.0.0",
++    "tslint": "^5.12.1",
++    "tslint-consistent-codestyle": "^1.15.0",
++    "typescript": "3.4"
++  },
++  "gitHead": "beac2b8c8badae230074d88cd0cd08da95daafc5",
++  "_id": "node-pty@0.9.0",
++  "_npmVersion": "6.4.1",
++  "_nodeVersion": "8.16.2",
++  "_npmUser": {
++    "name": "tyriar",
++    "email": "tyriar@tyriar.com"
++  },
++  "dist": {
++    "integrity": "sha512-MBnCQl83FTYOu7B4xWw10AW77AAh7ThCE1VXEv+JeWj8mSpGo+0bwgsV+b23ljBFwEM9OmsOv3kM27iUPPm84g==",
++    "shasum": "8f9bcc0d1c5b970a3184ffd533d862c7eb6590a6",
++    "tarball": "https://registry.npmjs.org/node-pty/-/node-pty-0.9.0.tgz",
++    "fileCount": 243,
++    "unpackedSize": 1079779,
++    "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdr0CpCRA9TVsSAnZWagAAvQoP/0G3Jy4bgYG7P44M7AkK\n7eegnmVgFp+t6PP7UqM4K6y8ex2/CLdl7UMRO0LFiJs7PnWGtEgXAIyC9Tmu\nJ8fkNly2/hAZdXU5C8E2NopUVb7QFjaaNshDkkVbn6pRiVG/Uo1Z4TW4Ijny\nqnDflc53cAzcepb2SnmNV7WqPUSlnY0jq2zPHJFfa4goj6+BU/V/VkYbH/eV\nFjejs5AufMRfG/3lM/R9/yNMNtNRraFRbZE9x6+yW6Wli4QPhw3ITJ1R2gPZ\nq2GjMRvrYmXWDr8pROrfAjSGpkaLpGNrIQbNDMtl5P9MfInBAH34zPurwV+J\ntx65FZ5ifCbeSU7b3f1JVkoLA09pAJpu/6Xk4xhsYfvacZxOcMCwlQ6UzAUA\n9gsVieq4acx1KbtlKIjvrgN3UrsdTvVDb5jlslD+7kD0Ux4jiXaiCblw0fyj\nMgxgN2xADa2wsihSgcSsW8wIp7X+K0VV5k0HgJ7iQpVtEZrN41UJ4hIH/toU\n+XEkQo1wqsjlXHVZocxIhwNYrSmoEWTlXW0OTC2tCWYkkIkY33JNRSEkWlHg\noNMjX4Gjt9769my7Us94K8yORg3xyEC0b859xSL70M71/zRuHFwn6hWa/z5i\nqmbLfyhz+AZkywh45CJ6H3BqSjLed/70CfVSfqy58j1NqcKy7oqtCiFjYWKf\nOwd4\r\n=jQ/c\r\n-----END PGP SIGNATURE-----\r\n"
++  },
++  "maintainers": [
++    {
++      "email": "alros@microsoft.com",
++      "name": "alexr00"
++    },
++    {
++      "email": "npmjs@microsoft.com",
++      "name": "microsoft"
++    },
++    {
++      "email": "tyriar@tyriar.com",
++      "name": "tyriar"
++    }
++  ],
++  "directories": {},
++  "_npmOperationalInternal": {
++    "host": "s3://npm-registry-packages",
++    "tmp": "tmp/node-pty_0.9.0_1571766440764_0.5541740518865894"
++  },
++  "_hasShrinkwrap": false,
++  "_shasum": "8f9bcc0d1c5b970a3184ffd533d862c7eb6590a6",
++  "_from": "node-pty@",
++  "_resolved": "https://registry.npmjs.org/node-pty/-/node-pty-0.9.0.tgz"
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d88b7f108b4a1a3429bf50d72884f9a5a84158f4
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,18 @@@
++'use strict'
++
++const os = require('os');
++const path = require('path');
++const spawn = require('child_process').spawn;
++
++const gypArgs = ['rebuild'];
++if (process.env.NODE_PTY_DEBUG) {
++  gypArgs.push('--debug');
++}
++const gypProcess = spawn(os.platform() === 'win32' ? 'node-gyp.cmd' : 'node-gyp', gypArgs, {
++  cwd: path.join(__dirname, '..'),
++  stdio: 'inherit'
++});
++
++gypProcess.on('exit', function (code) {
++  process.exit(code);
++});
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2c026ee5d756c97ce3cddb897a66a76f70f17386
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,41 @@@
++var fs = require('fs');
++var path = require('path');
++
++var RELEASE_DIR = path.join(__dirname, '..', 'build', 'Release');
++var BUILD_FILES = [
++  path.join(RELEASE_DIR, 'conpty.node'),
++  path.join(RELEASE_DIR, 'conpty.pdb'),
++  path.join(RELEASE_DIR, 'conpty_console_list.node'),
++  path.join(RELEASE_DIR, 'conpty_console_list.pdb'),
++  path.join(RELEASE_DIR, 'pty.node'),
++  path.join(RELEASE_DIR, 'pty.pdb'),
++  path.join(RELEASE_DIR, 'winpty-agent.exe'),
++  path.join(RELEASE_DIR, 'winpty-agent.pdb'),
++  path.join(RELEASE_DIR, 'winpty.dll'),
++  path.join(RELEASE_DIR, 'winpty.pdb')
++];
++
++cleanFolderRecursive = function(folder) {
++  var files = [];
++  if( fs.existsSync(folder) ) {
++    files = fs.readdirSync(folder);
++    files.forEach(function(file,index) {
++      var curPath = path.join(folder, file);
++      if(fs.lstatSync(curPath).isDirectory()) { // recurse
++        cleanFolderRecursive(curPath);
++        fs.rmdirSync(curPath);
++      } else if (BUILD_FILES.indexOf(curPath) < 0){ // delete file
++        fs.unlinkSync(curPath);
++      }
++    });
++  }
++};
++
++try {
++  cleanFolderRecursive(RELEASE_DIR);
++} catch(e) {
++  console.log(e);
++  //process.exit(1);
++} finally {
++  process.exit(0);
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..968531e14450e3f76a98ea547bcf969ae58f49e9
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,62 @@@
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++
++const cp = require('child_process');
++const fs = require('fs');
++const path = require('path');
++const packageJson = require('../package.json');
++
++// Setup auth
++fs.writeFileSync(`${process.env['HOME']}/.npmrc`, `//registry.npmjs.org/:_authToken=${process.env['NPM_AUTH_TOKEN']}`);
++
++// Determine if this is a stable or beta release
++const publishedVersions = getPublishedVersions();
++const isStableRelease = publishedVersions.indexOf(packageJson.version) === -1;
++
++// Get the next version
++let nextVersion = isStableRelease ? packageJson.version : getNextBetaVersion();
++console.log(`Publishing version: ${nextVersion}`);
++
++// Set the version in package.json
++const packageJsonFile = path.resolve(__dirname, '..', 'package.json');
++packageJson.version = nextVersion;
++fs.writeFileSync(packageJsonFile, JSON.stringify(packageJson, null, 2));
++
++// Publish
++const args = ['publish'];
++if (!isStableRelease) {
++  args.push('--tag', 'beta');
++}
++const result = cp.spawn('npm', args, { stdio: 'inherit' });
++result.on('exit', code => process.exit(code));
++
++function getNextBetaVersion() {
++  if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.exec(packageJson.version)) {
++    console.error('The package.json version must be of the form x.y.z');
++    process.exit(1);
++  }
++  const tag = 'beta';
++  const stableVersion = packageJson.version.split('.');
++  const nextStableVersion = `${stableVersion[0]}.${parseInt(stableVersion[1]) + 1}.0`;
++  const publishedVersions = getPublishedVersions(nextStableVersion, tag);
++  if (publishedVersions.length === 0) {
++    return `${nextStableVersion}-${tag}1`;
++  }
++  const latestPublishedVersion = publishedVersions.sort((a, b) => {
++    const aVersion = parseInt(a.substr(a.search(/[0-9]+$/)));
++    const bVersion = parseInt(b.substr(b.search(/[0-9]+$/)));
++    return aVersion > bVersion ? -1 : 1;
++  })[0];
++  const latestTagVersion = parseInt(latestPublishedVersion.substr(latestPublishedVersion.search(/[0-9]+$/)), 10);
++  return `${nextStableVersion}-${tag}${latestTagVersion + 1}`;
++}
++
++function getPublishedVersions(version, tag) {
++  const versionsProcess = cp.spawnSync('npm', ['view', packageJson.name, 'versions', '--json']);
++  const versionsJson = JSON.parse(versionsProcess.stdout);
++  if (tag) {
++    return versionsJson.filter(v => !v.search(new RegExp(`${version}-${tag}[0-9]+`)));
++  }
++  return versionsJson;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..2aec542534698fcc0586f64a6ae7b7fd2d37af9f
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,19 @@@
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ *
++ * This module fetches the console process list for a particular PID. It must be
++ * called from a different process (child_process.fork) as there can only be a
++ * single console attached to a process.
++ */
++
++let getConsoleProcessList: any;
++try {
++  getConsoleProcessList = require('../build/Release/conpty_console_list.node').getConsoleProcessList;
++} catch (err) {
++  getConsoleProcessList = require('../build/Debug/conpty_console_list.node').getConsoleProcessList;
++}
++
++const shellPid = parseInt(process.argv[2], 10);
++const consoleProcessList = getConsoleProcessList(shellPid);
++process.send({ consoleProcessList });
++process.exit(0);
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..a65bfc2a23e564f5ad1a15c8e6850139e278d4bb
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,30 @@@
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++
++import * as assert from 'assert';
++import { EventEmitter2 } from './eventEmitter2';
++
++describe('EventEmitter2', () => {
++  it('should fire listeners multiple times', () => {
++    const order: string[] = [];
++    const emitter = new EventEmitter2<number>();
++    emitter.event(data => order.push(data + 'a'));
++    emitter.event(data => order.push(data + 'b'));
++    emitter.fire(1);
++    emitter.fire(2);
++    assert.deepEqual(order, [ '1a', '1b', '2a', '2b' ]);
++  });
++
++  it('should not fire listeners once disposed', () => {
++    const order: string[] = [];
++    const emitter = new EventEmitter2<number>();
++    emitter.event(data => order.push(data + 'a'));
++    const disposeB = emitter.event(data => order.push(data + 'b'));
++    emitter.event(data => order.push(data + 'c'));
++    emitter.fire(1);
++    disposeB.dispose();
++    emitter.fire(2);
++    assert.deepEqual(order, [ '1a', '1b', '1c', '2a', '2c' ]);
++  });
++});
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6779d0cceae2ccc66cddf9bc2547f745e84a7fe1
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,48 @@@
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++
++import { IDisposable } from './types';
++
++interface IListener<T> {
++  (e: T): void;
++}
++
++export interface IEvent<T> {
++  (listener: (e: T) => any): IDisposable;
++}
++
++export class EventEmitter2<T> {
++  private _listeners: IListener<T>[] = [];
++  private _event?: IEvent<T>;
++
++  public get event(): IEvent<T> {
++    if (!this._event) {
++      this._event = (listener: (e: T) => any) => {
++        this._listeners.push(listener);
++        const disposable = {
++          dispose: () => {
++            for (let i = 0; i < this._listeners.length; i++) {
++              if (this._listeners[i] === listener) {
++                this._listeners.splice(i, 1);
++                return;
++              }
++            }
++          }
++        };
++        return disposable;
++      };
++    }
++    return this._event;
++  }
++
++  public fire(data: T): void {
++    const queue: IListener<T>[] = [];
++    for (let i = 0; i < this._listeners.length; i++) {
++      queue.push(this._listeners[i]);
++    }
++    for (let i = 0; i < queue.length; i++) {
++      queue[i].call(undefined, data);
++    }
++  }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..53d0322e5e5b75353eb7028a0279f10c6664b476
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,51 @@@
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import { ITerminal, IPtyOpenOptions, IPtyForkOptions, IWindowsPtyForkOptions } from './interfaces';
++import { ArgvOrCommandLine } from './types';
++
++let terminalCtor: any;
++if (process.platform === 'win32') {
++  terminalCtor = require('./windowsTerminal').WindowsTerminal;
++} else {
++  terminalCtor = require('./unixTerminal').UnixTerminal;
++}
++
++/**
++ * Forks a process as a pseudoterminal.
++ * @param file The file to launch.
++ * @param args The file's arguments as argv (string[]) or in a pre-escaped
++ * CommandLine format (string). Note that the CommandLine option is only
++ * available on Windows and is expected to be escaped properly.
++ * @param options The options of the terminal.
++ * @throws When the file passed to spawn with does not exists.
++ * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
++ * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
++ * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx
++ */
++export function spawn(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions | IWindowsPtyForkOptions): ITerminal {
++  return new terminalCtor(file, args, opt);
++}
++
++/** @deprecated */
++export function fork(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions | IWindowsPtyForkOptions): ITerminal {
++  return new terminalCtor(file, args, opt);
++}
++
++/** @deprecated */
++export function createTerminal(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions | IWindowsPtyForkOptions): ITerminal {
++  return new terminalCtor(file, args, opt);
++}
++
++export function open(options: IPtyOpenOptions): ITerminal {
++  return terminalCtor.open(options);
++}
++
++/**
++ * Expose the native API when not Windows, note that this is not public API and
++ * could be removed at any time.
++ */
++export const native = (process.platform !== 'win32' ? require('../build/Release/pty.node') : null);
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..f100e0edba23d9e9dcc4f4a8bedaa72a2805b136
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,136 @@@
++/**
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import * as net from 'net';
++
++export interface IProcessEnv {
++  [key: string]: string;
++}
++
++export interface ITerminal {
++  /**
++   * Gets the name of the process.
++   */
++  process: string;
++
++  /**
++   * Gets the process ID.
++   */
++  pid: number;
++
++  /**
++   * The socket for the master file descriptor. This is not supported on
++   * Windows.
++   */
++  master: net.Socket;
++
++  /**
++   * The socket for the slave file descriptor. This is not supported on Windows.
++   */
++  slave: net.Socket;
++
++  /**
++   * Writes data to the socket.
++   * @param data The data to write.
++   */
++  write(data: string): void;
++
++  /**
++   * Resize the pty.
++   * @param cols The number of columns.
++   * @param rows The number of rows.
++   */
++  resize(cols: number, rows: number): void;
++
++  /**
++   * Close, kill and destroy the socket.
++   */
++  destroy(): void;
++
++  /**
++   * Kill the pty.
++   * @param signal The signal to send, by default this is SIGHUP. This is not
++   * supported on Windows.
++   */
++  kill(signal?: string): void;
++
++  /**
++   * Set the pty socket encoding.
++   */
++  setEncoding(encoding: string | null): void;
++
++  /**
++   * Resume the pty socket.
++   */
++  resume(): void;
++
++  /**
++   * Pause the pty socket.
++   */
++  pause(): void;
++
++  /**
++   * Alias for ITerminal.on(eventName, listener).
++   */
++  addListener(eventName: string, listener: (...args: any[]) => any): void;
++
++  /**
++   * Adds the listener function to the end of the listeners array for the event
++   * named eventName.
++   * @param eventName The event name.
++   * @param listener The callback function
++   */
++  on(eventName: string, listener: (...args: any[]) => any): void;
++
++  /**
++   * Returns a copy of the array of listeners for the event named eventName.
++   */
++  listeners(eventName: string): Function[];
++
++  /**
++   * Removes the specified listener from the listener array for the event named
++   * eventName.
++   */
++  removeListener(eventName: string, listener: (...args: any[]) => any): void;
++
++  /**
++   * Removes all listeners, or those of the specified eventName.
++   */
++  removeAllListeners(eventName: string): void;
++
++  /**
++   * Adds a one time listener function for the event named eventName. The next
++   * time eventName is triggered, this listener is removed and then invoked.
++   */
++  once(eventName: string, listener: (...args: any[]) => any): void;
++}
++
++interface IBasePtyForkOptions {
++  name?: string;
++  cols?: number;
++  rows?: number;
++  cwd?: string;
++  env?: { [key: string]: string };
++  encoding?: string;
++  handleFlowControl?: boolean;
++  flowControlPause?: string;
++  flowControlResume?: string;
++}
++
++export interface IPtyForkOptions extends IBasePtyForkOptions {
++  uid?: number;
++  gid?: number;
++}
++
++export interface IWindowsPtyForkOptions extends IBasePtyForkOptions {
++  useConpty?: boolean;
++  conptyInheritCursor?: boolean;
++}
++
++export interface IPtyOpenOptions {
++  cols?: number;
++  rows?: number;
++  encoding?: string;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..3212e3b777bb17d20f9e4464de7fc50c58b59072
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,54 @@@
++/**
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++interface IConptyNative {
++  startProcess(file: string, cols: number, rows: number, debug: boolean, pipeName: string, conptyInheritCursor: boolean): IConptyProcess;
++  connect(ptyId: number, commandLine: string, cwd: string, env: string[], onExitCallback: (exitCode: number) => void): { pid: number };
++  resize(ptyId: number, cols: number, rows: number): void;
++  kill(ptyId: number): void;
++}
++
++interface IWinptyNative {
++  startProcess(file: string, commandLine: string, env: string[], cwd: string, cols: number, rows: number, debug: boolean): IWinptyProcess;
++  resize(processHandle: number, cols: number, rows: number): void;
++  kill(pid: number, innerPidHandle: number): void;
++  getProcessList(pid: number): number[];
++  getExitCode(innerPidHandle: number): number;
++}
++
++interface IUnixNative {
++  fork(file: string, args: string[], parsedEnv: string[], cwd: string, cols: number, rows: number, uid: number, gid: number, useUtf8: boolean, onExitCallback: (code: number, signal: number) => void): IUnixProcess;
++  open(cols: number, rows: number): IUnixOpenProcess;
++  process(fd: number, pty: string): string;
++  resize(fd: number, cols: number, rows: number): void;
++}
++
++interface IConptyProcess {
++  pty: number;
++  fd: number;
++  conin: string;
++  conout: string;
++}
++
++interface IWinptyProcess {
++  pty: number;
++  fd: number;
++  conin: string;
++  conout: string;
++  pid: number;
++  innerPid: number;
++  innerPidHandle: number;
++}
++
++interface IUnixProcess {
++  fd: number;
++  pid: number;
++  pty: string;
++}
++
++interface IUnixOpenProcess {
++  master: number;
++  slave: number;
++  pty: string;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..dba011fb7f880985033377a5f326231b2ba6892a
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,66 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import * as assert from 'assert';
++import { WindowsTerminal } from './windowsTerminal';
++import { UnixTerminal } from './unixTerminal';
++import { pollUntil } from './testUtils.test';
++
++const terminalConstructor = (process.platform === 'win32') ? WindowsTerminal : UnixTerminal;
++const SHELL = (process.platform === 'win32') ? 'cmd.exe' : '/bin/bash';
++
++let terminalCtor: WindowsTerminal | UnixTerminal;
++if (process.platform === 'win32') {
++  terminalCtor = require('./windowsTerminal');
++} else {
++  terminalCtor = require('./unixTerminal');
++}
++
++
++describe('Terminal', () => {
++  describe('constructor', () => {
++    it('should do basic type checks', () => {
++      assert.throws(
++        () => new (<any>terminalCtor)('a', 'b', { 'name': {} }),
++        'name must be a string (not a object)'
++      );
++    });
++  });
++
++  describe('automatic flow control', () => {
++    it('should respect ctor flow control options', () => {
++      const pty = new terminalConstructor(SHELL, [], {handleFlowControl: true, flowControlPause: 'abc', flowControlResume: '123'});
++      assert.equal(pty.handleFlowControl, true);
++      assert.equal((pty as any)._flowControlPause, 'abc');
++      assert.equal((pty as any)._flowControlResume, '123');
++    });
++    // TODO: I don't think this test ever worked due to pollUntil being used incorrectly
++    // it('should do flow control automatically', async function(): Promise<void> {
++    //   // Flow control doesn't work on Windows
++    //   if (process.platform === 'win32') {
++    //     return;
++    //   }
++
++    //   this.timeout(10000);
++    //   const pty = new terminalConstructor(SHELL, [], {handleFlowControl: true, flowControlPause: 'PAUSE', flowControlResume: 'RESUME'});
++    //   let read: string = '';
++    //   pty.on('data', data => read += data);
++    //   pty.on('pause', () => read += 'paused');
++    //   pty.on('resume', () => read += 'resumed');
++    //   pty.write('1');
++    //   pty.write('PAUSE');
++    //   pty.write('2');
++    //   pty.write('RESUME');
++    //   pty.write('3');
++    //   await pollUntil(() => {
++    //     return stripEscapeSequences(read).endsWith('1pausedresumed23');
++    //   }, 100, 10);
++    // });
++  });
++});
++
++function stripEscapeSequences(data: string): string {
++  return data.replace(/\u001b\[0K/, '');
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..fb7f60908c2693831151379c2af25f217295ea87
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,195 @@@
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import { Socket } from 'net';
++import { EventEmitter } from 'events';
++import { ITerminal, IPtyForkOptions } from './interfaces';
++import { EventEmitter2, IEvent } from './eventEmitter2';
++import { IExitEvent } from './types';
++
++export const DEFAULT_COLS: number = 80;
++export const DEFAULT_ROWS: number = 24;
++
++/**
++ * Default messages to indicate PAUSE/RESUME for automatic flow control.
++ * To avoid conflicts with rebound XON/XOFF control codes (such as on-my-zsh),
++ * the sequences can be customized in `IPtyForkOptions`.
++ */
++const FLOW_CONTROL_PAUSE =  '\x13';   // defaults to XOFF
++const FLOW_CONTROL_RESUME = '\x11';   // defaults to XON
++
++export abstract class Terminal implements ITerminal {
++  protected _socket: Socket;
++  protected _pid: number;
++  protected _fd: number;
++  protected _pty: any;
++
++  protected _file: string;
++  protected _name: string;
++  protected _cols: number;
++  protected _rows: number;
++
++  protected _readable: boolean;
++  protected _writable: boolean;
++
++  protected _internalee: EventEmitter;
++  private _flowControlPause: string;
++  private _flowControlResume: string;
++  public handleFlowControl: boolean;
++
++  private _onData = new EventEmitter2<string>();
++  public get onData(): IEvent<string> { return this._onData.event; }
++  private _onExit = new EventEmitter2<IExitEvent>();
++  public get onExit(): IEvent<IExitEvent> { return this._onExit.event; }
++
++  public get pid(): number { return this._pid; }
++  public get cols(): number { return this._cols; }
++  public get rows(): number { return this._rows; }
++
++  constructor(opt?: IPtyForkOptions) {
++    // for 'close'
++    this._internalee = new EventEmitter();
++
++    if (!opt) {
++      return;
++    }
++
++    // Do basic type checks here in case node-pty is being used within JavaScript. If the wrong
++    // types go through to the C++ side it can lead to hard to diagnose exceptions.
++    this._checkType('name', opt.name ? opt.name : null, 'string');
++    this._checkType('cols', opt.cols ? opt.cols : null, 'number');
++    this._checkType('rows', opt.rows ? opt.rows : null, 'number');
++    this._checkType('cwd', opt.cwd ? opt.cwd : null, 'string');
++    this._checkType('env', opt.env ? opt.env : null, 'object');
++    this._checkType('uid', opt.uid ? opt.uid : null, 'number');
++    this._checkType('gid', opt.gid ? opt.gid : null, 'number');
++    this._checkType('encoding', opt.encoding ? opt.encoding : null, 'string');
++
++    // setup flow control handling
++    this.handleFlowControl = !!(opt.handleFlowControl);
++    this._flowControlPause = opt.flowControlPause || FLOW_CONTROL_PAUSE;
++    this._flowControlResume = opt.flowControlResume || FLOW_CONTROL_RESUME;
++  }
++
++  protected abstract _write(data: string): void;
++
++  public write(data: string): void {
++    if (this.handleFlowControl) {
++      // PAUSE/RESUME messages are not forwarded to the pty
++      if (data === this._flowControlPause) {
++        this.pause();
++        return;
++      }
++      if (data === this._flowControlResume) {
++        this.resume();
++        return;
++      }
++    }
++    // everything else goes to the real pty
++    this._write(data);
++  }
++
++  protected _forwardEvents(): void {
++    this.on('data', e => this._onData.fire(e));
++    this.on('exit', (exitCode, signal) => this._onExit.fire({ exitCode, signal }));
++  }
++
++  private _checkType(name: string, value: any, type: string): void {
++    if (value && typeof value !== type) {
++      throw new Error(`${name} must be a ${type} (not a ${typeof value})`);
++    }
++  }
++
++  /** See net.Socket.end */
++  public end(data: string): void {
++    this._socket.end(data);
++  }
++
++  /** See stream.Readable.pipe */
++  public pipe(dest: any, options: any): any {
++    return this._socket.pipe(dest, options);
++  }
++
++  /** See net.Socket.pause */
++  public pause(): Socket {
++    return this._socket.pause();
++  }
++
++  /** See net.Socket.resume */
++  public resume(): Socket {
++    return this._socket.resume();
++  }
++
++  /** See net.Socket.setEncoding */
++  public setEncoding(encoding: string | null): void {
++    if ((<any>this._socket)._decoder) {
++      delete (<any>this._socket)._decoder;
++    }
++    if (encoding) {
++      this._socket.setEncoding(encoding);
++    }
++  }
++
++  public addListener(eventName: string, listener: (...args: any[]) => any): void { this.on(eventName, listener); }
++  public on(eventName: string, listener: (...args: any[]) => any): void {
++    if (eventName === 'close') {
++      this._internalee.on('close', listener);
++      return;
++    }
++    this._socket.on(eventName, listener);
++  }
++
++  public emit(eventName: string, ...args: any[]): any {
++    if (eventName === 'close') {
++      return this._internalee.emit.apply(this._internalee, arguments);
++    }
++    return this._socket.emit.apply(this._socket, arguments);
++  }
++
++  public listeners(eventName: string): Function[] {
++    return this._socket.listeners(eventName);
++  }
++
++  public removeListener(eventName: string, listener: (...args: any[]) => any): void {
++    this._socket.removeListener(eventName, listener);
++  }
++
++  public removeAllListeners(eventName: string): void {
++    this._socket.removeAllListeners(eventName);
++  }
++
++  public once(eventName: string, listener: (...args: any[]) => any): void {
++    this._socket.once(eventName, listener);
++  }
++
++  public abstract resize(cols: number, rows: number): void;
++  public abstract destroy(): void;
++  public abstract kill(signal?: string): void;
++
++  public abstract get process(): string;
++  public abstract get master(): Socket;
++  public abstract get slave(): Socket;
++
++  protected _close(): void {
++    this._socket.writable = false;
++    this._socket.readable = false;
++    this.write = () => {};
++    this.end = () => {};
++    this._writable = false;
++    this._readable = false;
++  }
++
++  protected _parseEnv(env: {[key: string]: string}): string[] {
++    const keys = Object.keys(env || {});
++    const pairs = [];
++
++    for (let i = 0; i < keys.length; i++) {
++      pairs.push(keys[i] + '=' + env[keys[i]]);
++    }
++
++    return pairs;
++  }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..0bdabffaf13ae42521256f7d30b864fc78a45a35
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,23 @@@
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++
++export function pollUntil(cb: () => boolean, timeout: number, interval: number): Promise<void> {
++  return new Promise<void>((resolve, reject) => {
++    const intervalId = setInterval(() => {
++      if (cb()) {
++        clearInterval(intervalId);
++        clearTimeout(timeoutId);
++        resolve();
++      }
++    }, interval);
++    const timeoutId = setTimeout(() => {
++      clearInterval(intervalId);
++      if (cb()) {
++        resolve();
++      } else {
++        reject();
++      }
++    }, timeout);
++  });
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..94c2ac747baa8d7c8d30708b5ae20fc866c1c3c3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,15 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++export type ArgvOrCommandLine = string[] | string;
++
++export interface IExitEvent {
++  exitCode: number;
++  signal: number | undefined;
++}
++
++export interface IDisposable {
++  dispose(): void;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..d2f4c1131d7e91c714682e336848d764cc947620
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,708 @@@
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
++ * Copyright (c) 2017, Daniel Imms (MIT License)
++ *
++ * pty.cc:
++ *   This file is responsible for starting processes
++ *   with pseudo-terminal file descriptors.
++ *
++ * See:
++ *   man pty
++ *   man tty_ioctl
++ *   man termios
++ *   man forkpty
++ */
++
++/**
++ * Includes
++ */
++
++#include <nan.h>
++#include <errno.h>
++#include <string.h>
++#include <stdlib.h>
++#include <unistd.h>
++
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <sys/ioctl.h>
++#include <sys/wait.h>
++#include <fcntl.h>
++
++/* forkpty */
++/* http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html */
++#if defined(__GLIBC__) || defined(__CYGWIN__)
++#include <pty.h>
++#elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__)
++#include <util.h>
++#elif defined(__FreeBSD__)
++#include <libutil.h>
++#elif defined(__sun)
++#include <stropts.h> /* for I_PUSH */
++#else
++#include <pty.h>
++#endif
++
++#include <termios.h> /* tcgetattr, tty_ioctl */
++
++/* Some platforms name VWERASE and VDISCARD differently */
++#if !defined(VWERASE) && defined(VWERSE)
++#define VWERASE       VWERSE
++#endif
++#if !defined(VDISCARD) && defined(VDISCRD)
++#define VDISCARD      VDISCRD
++#endif
++
++/* environ for execvpe */
++/* node/src/node_child_process.cc */
++#if defined(__APPLE__) && !TARGET_OS_IPHONE
++#include <crt_externs.h>
++#define environ (*_NSGetEnviron())
++#else
++extern char **environ;
++#endif
++
++/* for pty_getproc */
++#if defined(__linux__)
++#include <stdio.h>
++#include <stdint.h>
++#elif defined(__APPLE__)
++#include <sys/sysctl.h>
++#include <libproc.h>
++#endif
++
++/**
++ * Structs
++ */
++
++struct pty_baton {
++  Nan::Persistent<v8::Function> cb;
++  int exit_code;
++  int signal_code;
++  pid_t pid;
++  uv_async_t async;
++  uv_thread_t tid;
++};
++
++/**
++ * Methods
++ */
++
++NAN_METHOD(PtyFork);
++NAN_METHOD(PtyOpen);
++NAN_METHOD(PtyResize);
++NAN_METHOD(PtyGetProc);
++
++/**
++ * Functions
++ */
++
++static int
++pty_execvpe(const char *, char **, char **);
++
++static int
++pty_nonblock(int);
++
++static char *
++pty_getproc(int, char *);
++
++static int
++pty_openpty(int *, int *, char *,
++            const struct termios *,
++            const struct winsize *);
++
++static pid_t
++pty_forkpty(int *, char *,
++            const struct termios *,
++            const struct winsize *);
++
++static void
++pty_waitpid(void *);
++
++static void
++pty_after_waitpid(uv_async_t *);
++
++static void
++pty_after_close(uv_handle_t *);
++
++NAN_METHOD(PtyFork) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 10 ||
++      !info[0]->IsString() ||
++      !info[1]->IsArray() ||
++      !info[2]->IsArray() ||
++      !info[3]->IsString() ||
++      !info[4]->IsNumber() ||
++      !info[5]->IsNumber() ||
++      !info[6]->IsNumber() ||
++      !info[7]->IsNumber() ||
++      !info[8]->IsBoolean() ||
++      !info[9]->IsFunction()) {
++    return Nan::ThrowError(
++        "Usage: pty.fork(file, args, env, cwd, cols, rows, uid, gid, utf8, onexit)");
++  }
++
++  // Make sure the process still listens to SIGINT
++  signal(SIGINT, SIG_DFL);
++
++  // file
++  Nan::Utf8String file(info[0]);
++
++  // args
++  int i = 0;
++  v8::Local<v8::Array> argv_ = v8::Local<v8::Array>::Cast(info[1]);
++  int argc = argv_->Length();
++  int argl = argc + 1 + 1;
++  char **argv = new char*[argl];
++  argv[0] = strdup(*file);
++  argv[argl-1] = NULL;
++  for (; i < argc; i++) {
++    Nan::Utf8String arg(Nan::Get(argv_, i).ToLocalChecked());
++    argv[i+1] = strdup(*arg);
++  }
++
++  // env
++  i = 0;
++  v8::Local<v8::Array> env_ = v8::Local<v8::Array>::Cast(info[2]);
++  int envc = env_->Length();
++  char **env = new char*[envc+1];
++  env[envc] = NULL;
++  for (; i < envc; i++) {
++    Nan::Utf8String pair(Nan::Get(env_, i).ToLocalChecked());
++    env[i] = strdup(*pair);
++  }
++
++  // cwd
++  Nan::Utf8String cwd_(info[3]);
++  char *cwd = strdup(*cwd_);
++
++  // size
++  struct winsize winp;
++  winp.ws_col = info[4]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  winp.ws_row = info[5]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  winp.ws_xpixel = 0;
++  winp.ws_ypixel = 0;
++
++  // termios
++  struct termios t = termios();
++  struct termios *term = &t;
++  term->c_iflag = ICRNL | IXON | IXANY | IMAXBEL | BRKINT;
++  if (Nan::To<bool>(info[8]).FromJust()) {
++#if defined(IUTF8)
++    term->c_iflag |= IUTF8;
++#endif
++  }
++  term->c_oflag = OPOST | ONLCR;
++  term->c_cflag = CREAD | CS8 | HUPCL;
++  term->c_lflag = ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL;
++
++  term->c_cc[VEOF] = 4;
++  term->c_cc[VEOL] = -1;
++  term->c_cc[VEOL2] = -1;
++  term->c_cc[VERASE] = 0x7f;
++  term->c_cc[VWERASE] = 23;
++  term->c_cc[VKILL] = 21;
++  term->c_cc[VREPRINT] = 18;
++  term->c_cc[VINTR] = 3;
++  term->c_cc[VQUIT] = 0x1c;
++  term->c_cc[VSUSP] = 26;
++  term->c_cc[VSTART] = 17;
++  term->c_cc[VSTOP] = 19;
++  term->c_cc[VLNEXT] = 22;
++  term->c_cc[VDISCARD] = 15;
++  term->c_cc[VMIN] = 1;
++  term->c_cc[VTIME] = 0;
++
++  #if (__APPLE__)
++  term->c_cc[VDSUSP] = 25;
++  term->c_cc[VSTATUS] = 20;
++  #endif
++
++  cfsetispeed(term, B38400);
++  cfsetospeed(term, B38400);
++
++  // uid / gid
++  int uid = info[6]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  int gid = info[7]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++
++  // fork the pty
++  int master = -1;
++  pid_t pid = pty_forkpty(&master, nullptr, term, &winp);
++
++  if (pid) {
++    for (i = 0; i < argl; i++) free(argv[i]);
++    delete[] argv;
++    for (i = 0; i < envc; i++) free(env[i]);
++    delete[] env;
++    free(cwd);
++  }
++
++  switch (pid) {
++    case -1:
++      return Nan::ThrowError("forkpty(3) failed.");
++    case 0:
++      if (strlen(cwd)) {
++        if (chdir(cwd) == -1) {
++          perror("chdir(2) failed.");
++          _exit(1);
++        }
++      }
++
++      if (uid != -1 && gid != -1) {
++        if (setgid(gid) == -1) {
++          perror("setgid(2) failed.");
++          _exit(1);
++        }
++        if (setuid(uid) == -1) {
++          perror("setuid(2) failed.");
++          _exit(1);
++        }
++      }
++
++      pty_execvpe(argv[0], argv, env);
++
++      perror("execvp(3) failed.");
++      _exit(1);
++    default:
++      if (pty_nonblock(master) == -1) {
++        return Nan::ThrowError("Could not set master fd to nonblocking.");
++      }
++
++      v8::Local<v8::Object> obj = Nan::New<v8::Object>();
++      Nan::Set(obj,
++        Nan::New<v8::String>("fd").ToLocalChecked(),
++        Nan::New<v8::Number>(master));
++      Nan::Set(obj,
++        Nan::New<v8::String>("pid").ToLocalChecked(),
++        Nan::New<v8::Number>(pid));
++      Nan::Set(obj,
++        Nan::New<v8::String>("pty").ToLocalChecked(),
++        Nan::New<v8::String>(ptsname(master)).ToLocalChecked());
++
++      pty_baton *baton = new pty_baton();
++      baton->exit_code = 0;
++      baton->signal_code = 0;
++      baton->cb.Reset(v8::Local<v8::Function>::Cast(info[9]));
++      baton->pid = pid;
++      baton->async.data = baton;
++
++      uv_async_init(uv_default_loop(), &baton->async, pty_after_waitpid);
++
++      uv_thread_create(&baton->tid, pty_waitpid, static_cast<void*>(baton));
++
++      return info.GetReturnValue().Set(obj);
++  }
++
++  return info.GetReturnValue().SetUndefined();
++}
++
++NAN_METHOD(PtyOpen) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 2 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsNumber()) {
++    return Nan::ThrowError("Usage: pty.open(cols, rows)");
++  }
++
++  // size
++  struct winsize winp;
++  winp.ws_col = info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  winp.ws_row = info[1]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  winp.ws_xpixel = 0;
++  winp.ws_ypixel = 0;
++
++  // pty
++  int master, slave;
++  int ret = pty_openpty(&master, &slave, nullptr, NULL, &winp);
++
++  if (ret == -1) {
++    return Nan::ThrowError("openpty(3) failed.");
++  }
++
++  if (pty_nonblock(master) == -1) {
++    return Nan::ThrowError("Could not set master fd to nonblocking.");
++  }
++
++  if (pty_nonblock(slave) == -1) {
++    return Nan::ThrowError("Could not set slave fd to nonblocking.");
++  }
++
++  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
++  Nan::Set(obj,
++    Nan::New<v8::String>("master").ToLocalChecked(),
++    Nan::New<v8::Number>(master));
++  Nan::Set(obj,
++    Nan::New<v8::String>("slave").ToLocalChecked(),
++    Nan::New<v8::Number>(slave));
++  Nan::Set(obj,
++    Nan::New<v8::String>("pty").ToLocalChecked(),
++    Nan::New<v8::String>(ptsname(master)).ToLocalChecked());
++
++  return info.GetReturnValue().Set(obj);
++}
++
++NAN_METHOD(PtyResize) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 3 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsNumber() ||
++      !info[2]->IsNumber()) {
++    return Nan::ThrowError("Usage: pty.resize(fd, cols, rows)");
++  }
++
++  int fd = info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++
++  struct winsize winp;
++  winp.ws_col = info[1]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  winp.ws_row = info[2]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++  winp.ws_xpixel = 0;
++  winp.ws_ypixel = 0;
++
++  if (ioctl(fd, TIOCSWINSZ, &winp) == -1) {
++    switch (errno) {
++      case EBADF: return Nan::ThrowError("ioctl(2) failed, EBADF");
++      case EFAULT: return Nan::ThrowError("ioctl(2) failed, EFAULT");
++      case EINVAL: return Nan::ThrowError("ioctl(2) failed, EINVAL");
++      case ENOTTY: return Nan::ThrowError("ioctl(2) failed, ENOTTY");
++    }
++    return Nan::ThrowError("ioctl(2) failed");
++  }
++
++  return info.GetReturnValue().SetUndefined();
++}
++
++/**
++ * Foreground Process Name
++ */
++NAN_METHOD(PtyGetProc) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 2 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsString()) {
++    return Nan::ThrowError("Usage: pty.process(fd, tty)");
++  }
++
++  int fd = info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust();
++
++  Nan::Utf8String tty_(info[1]);
++  char *tty = strdup(*tty_);
++  char *name = pty_getproc(fd, tty);
++  free(tty);
++
++  if (name == NULL) {
++    return info.GetReturnValue().SetUndefined();
++  }
++
++  v8::Local<v8::String> name_ = Nan::New<v8::String>(name).ToLocalChecked();
++  free(name);
++  return info.GetReturnValue().Set(name_);
++}
++
++/**
++ * execvpe
++ */
++
++// execvpe(3) is not portable.
++// http://www.gnu.org/software/gnulib/manual/html_node/execvpe.html
++static int
++pty_execvpe(const char *file, char **argv, char **envp) {
++  char **old = environ;
++  environ = envp;
++  int ret = execvp(file, argv);
++  environ = old;
++  return ret;
++}
++
++/**
++ * Nonblocking FD
++ */
++
++static int
++pty_nonblock(int fd) {
++  int flags = fcntl(fd, F_GETFL, 0);
++  if (flags == -1) return -1;
++  return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
++}
++
++/**
++ * pty_waitpid
++ * Wait for SIGCHLD to read exit status.
++ */
++
++static void
++pty_waitpid(void *data) {
++  int ret;
++  int stat_loc;
++
++  pty_baton *baton = static_cast<pty_baton*>(data);
++
++  errno = 0;
++
++  if ((ret = waitpid(baton->pid, &stat_loc, 0)) != baton->pid) {
++    if (ret == -1 && errno == EINTR) {
++      return pty_waitpid(baton);
++    }
++    if (ret == -1 && errno == ECHILD) {
++      // XXX node v0.8.x seems to have this problem.
++      // waitpid is already handled elsewhere.
++      ;
++    } else {
++      assert(false);
++    }
++  }
++
++  if (WIFEXITED(stat_loc)) {
++    baton->exit_code = WEXITSTATUS(stat_loc); // errno?
++  }
++
++  if (WIFSIGNALED(stat_loc)) {
++    baton->signal_code = WTERMSIG(stat_loc);
++  }
++
++  uv_async_send(&baton->async);
++}
++
++/**
++ * pty_after_waitpid
++ * Callback after exit status has been read.
++ */
++
++static void
++pty_after_waitpid(uv_async_t *async) {
++  Nan::HandleScope scope;
++  pty_baton *baton = static_cast<pty_baton*>(async->data);
++
++  v8::Local<v8::Value> argv[] = {
++    Nan::New<v8::Integer>(baton->exit_code),
++    Nan::New<v8::Integer>(baton->signal_code),
++  };
++
++  v8::Local<v8::Function> cb = Nan::New<v8::Function>(baton->cb);
++  baton->cb.Reset();
++  memset(&baton->cb, -1, sizeof(baton->cb));
++  Nan::AsyncResource resource("pty_after_waitpid");
++  resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), cb, 2, argv);
++
++  uv_close((uv_handle_t *)async, pty_after_close);
++}
++
++/**
++ * pty_after_close
++ * uv_close() callback - free handle data
++ */
++
++static void
++pty_after_close(uv_handle_t *handle) {
++  uv_async_t *async = (uv_async_t *)handle;
++  pty_baton *baton = static_cast<pty_baton*>(async->data);
++  delete baton;
++}
++
++/**
++ * pty_getproc
++ * Taken from tmux.
++ */
++
++// Taken from: tmux (http://tmux.sourceforge.net/)
++// Copyright (c) 2009 Nicholas Marriott <nicm@users.sourceforge.net>
++// Copyright (c) 2009 Joshua Elsasser <josh@elsasser.org>
++// Copyright (c) 2009 Todd Carson <toc@daybefore.net>
++//
++// Permission to use, copy, modify, and distribute this software for any
++// purpose with or without fee is hereby granted, provided that the above
++// copyright notice and this permission notice appear in all copies.
++//
++// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
++// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
++// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
++// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
++// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
++// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
++// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
++
++#if defined(__linux__)
++
++static char *
++pty_getproc(int fd, char *tty) {
++  FILE *f;
++  char *path, *buf;
++  size_t len;
++  int ch;
++  pid_t pgrp;
++  int r;
++
++  if ((pgrp = tcgetpgrp(fd)) == -1) {
++    return NULL;
++  }
++
++  r = asprintf(&path, "/proc/%lld/cmdline", (long long)pgrp);
++  if (r == -1 || path == NULL) return NULL;
++
++  if ((f = fopen(path, "r")) == NULL) {
++    free(path);
++    return NULL;
++  }
++
++  free(path);
++
++  len = 0;
++  buf = NULL;
++  while ((ch = fgetc(f)) != EOF) {
++    if (ch == '\0') break;
++    buf = (char *)realloc(buf, len + 2);
++    if (buf == NULL) return NULL;
++    buf[len++] = ch;
++  }
++
++  if (buf != NULL) {
++    buf[len] = '\0';
++  }
++
++  fclose(f);
++  return buf;
++}
++
++#elif defined(__APPLE__)
++
++static char *
++pty_getproc(int fd, char *tty) {
++  int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
++  size_t size;
++  struct kinfo_proc kp;
++
++  if ((mib[3] = tcgetpgrp(fd)) == -1) {
++    return NULL;
++  }
++
++  size = sizeof kp;
++  if (sysctl(mib, 4, &kp, &size, NULL, 0) == -1) {
++    return NULL;
++  }
++
++  if (*kp.kp_proc.p_comm == '\0') {
++    return NULL;
++  }
++
++  return strdup(kp.kp_proc.p_comm);
++}
++
++#else
++
++static char *
++pty_getproc(int fd, char *tty) {
++  return NULL;
++}
++
++#endif
++
++/**
++ * openpty(3) / forkpty(3)
++ */
++
++static int
++pty_openpty(int *amaster,
++            int *aslave,
++            char *name,
++            const struct termios *termp,
++            const struct winsize *winp) {
++#if defined(__sun)
++  char *slave_name;
++  int slave;
++  int master = open("/dev/ptmx", O_RDWR | O_NOCTTY);
++  if (master == -1) return -1;
++  if (amaster) *amaster = master;
++
++  if (grantpt(master) == -1) goto err;
++  if (unlockpt(master) == -1) goto err;
++
++  slave_name = ptsname(master);
++  if (slave_name == NULL) goto err;
++  if (name) strcpy(name, slave_name);
++
++  slave = open(slave_name, O_RDWR | O_NOCTTY);
++  if (slave == -1) goto err;
++  if (aslave) *aslave = slave;
++
++  ioctl(slave, I_PUSH, "ptem");
++  ioctl(slave, I_PUSH, "ldterm");
++  ioctl(slave, I_PUSH, "ttcompat");
++
++  if (termp) tcsetattr(slave, TCSAFLUSH, termp);
++  if (winp) ioctl(slave, TIOCSWINSZ, winp);
++
++  return 0;
++
++err:
++  close(master);
++  return -1;
++#else
++  return openpty(amaster, aslave, name, (termios *)termp, (winsize *)winp);
++#endif
++}
++
++static pid_t
++pty_forkpty(int *amaster,
++            char *name,
++            const struct termios *termp,
++            const struct winsize *winp) {
++#if defined(__sun)
++  int master, slave;
++
++  int ret = pty_openpty(&master, &slave, name, termp, winp);
++  if (ret == -1) return -1;
++  if (amaster) *amaster = master;
++
++  pid_t pid = fork();
++
++  switch (pid) {
++    case -1:
++      close(master);
++      close(slave);
++      return -1;
++    case 0:
++      close(master);
++
++      setsid();
++
++#if defined(TIOCSCTTY)
++      // glibc does this
++      if (ioctl(slave, TIOCSCTTY, NULL) == -1) {
++        _exit(1);
++      }
++#endif
++
++      dup2(slave, 0);
++      dup2(slave, 1);
++      dup2(slave, 2);
++
++      if (slave > 2) close(slave);
++
++      return 0;
++    default:
++      close(slave);
++      return pid;
++  }
++
++  return -1;
++#else
++  return forkpty(amaster, name, (termios *)termp, (winsize *)winp);
++#endif
++}
++
++/**
++ * Init
++ */
++
++NAN_MODULE_INIT(init) {
++  Nan::HandleScope scope;
++  Nan::Export(target, "fork", PtyFork);
++  Nan::Export(target, "open", PtyOpen);
++  Nan::Export(target, "resize", PtyResize);
++  Nan::Export(target, "process", PtyGetProc);
++}
++
++NODE_MODULE(pty, init)
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b9d330fc5246044ff99b1386b32383c453cda9ab
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,108 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import { UnixTerminal } from './unixTerminal';
++import * as assert from 'assert';
++import * as path from 'path';
++import { pollUntil } from './testUtils.test';
++
++const FIXTURES_PATH = path.normalize(path.join(__dirname, '..', 'fixtures', 'utf8-character.txt'));
++
++if (process.platform !== 'win32') {
++  describe('UnixTerminal', () => {
++    describe('Constructor', () => {
++      it('should set a valid pts name', () => {
++        const term = new UnixTerminal('/bin/bash', [], {});
++        let regExp;
++        if (process.platform === 'linux') {
++          // https://linux.die.net/man/4/pts
++          regExp = /^\/dev\/pts\/\d+$/;
++        }
++        if (process.platform === 'darwin') {
++          // https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man4/pty.4.html
++          regExp = /^\/dev\/tty[p-sP-S][a-z0-9]+$/;
++        }
++        if (regExp) {
++          assert.ok(regExp.test((<any>term)._pty), '"' + (<any>term)._pty + '" should match ' + regExp.toString());
++        }
++      });
++    });
++
++    describe('PtyForkEncodingOption', () => {
++      it('should default to utf8', (done) => {
++        const term = new UnixTerminal('/bin/bash', [ '-c', `cat "${FIXTURES_PATH}"` ]);
++        term.on('data', (data) => {
++          assert.equal(typeof data, 'string');
++          assert.equal(data, '\u00E6');
++          done();
++        });
++      });
++      it('should return a Buffer when encoding is null', (done) => {
++        const term = new UnixTerminal('/bin/bash', [ '-c', `cat "${FIXTURES_PATH}"` ], {
++          encoding: null
++        });
++        term.on('data', (data) => {
++          assert.equal(typeof data, 'object');
++          assert.ok(data instanceof Buffer);
++          assert.equal(0xC3, data[0]);
++          assert.equal(0xA6, data[1]);
++          done();
++        });
++      });
++      it('should support other encodings', (done) => {
++        const text = 'test æ!';
++        const term = new UnixTerminal(null, ['-c', 'echo "' + text + '"'], {
++          encoding: 'base64'
++        });
++        let buffer = '';
++        term.on('data', (data) => {
++          assert.equal(typeof data, 'string');
++          buffer += data;
++        });
++        term.on('exit', () => {
++          assert.equal(Buffer.alloc(8, buffer, 'base64').toString().replace('\r', '').replace('\n', ''), text);
++          done();
++        });
++      });
++    });
++
++    describe('open', () => {
++      let term: UnixTerminal;
++
++      afterEach(() => {
++        if (term) {
++          term.slave.destroy();
++          term.master.destroy();
++        }
++      });
++
++      it('should open a pty with access to a master and slave socket', (done) => {
++        let doneCalled = false;
++        term = UnixTerminal.open({});
++
++        let slavebuf = '';
++        term.slave.on('data', (data) => {
++          slavebuf += data;
++        });
++
++        let masterbuf = '';
++        term.master.on('data', (data) => {
++          masterbuf += data;
++        });
++
++        pollUntil(() => {
++          if (masterbuf === 'slave\r\nmaster\r\n' && slavebuf === 'master\n') {
++            done();
++            return true;
++          }
++          return false;
++        }, 200, 10);
++
++        term.slave.write('slave\n');
++        term.master.write('master\n');
++      });
++    });
++  });
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..58e45677eee863128dabb0274ad0c7916890f222
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,299 @@@
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++import * as net from 'net';
++import { Terminal, DEFAULT_COLS, DEFAULT_ROWS } from './terminal';
++import { IProcessEnv, IPtyForkOptions, IPtyOpenOptions } from './interfaces';
++import { ArgvOrCommandLine } from './types';
++import { assign } from './utils';
++
++let pty: IUnixNative;
++try {
++  pty = require('../build/Release/pty.node');
++} catch (outerError) {
++  try {
++    pty = require('../build/Debug/pty.node');
++  } catch (innerError) {
++    console.error('innerError', innerError);
++    // Re-throw the exception from the Release require if the Debug require fails as well
++    throw outerError;
++  }
++}
++
++const DEFAULT_FILE = 'sh';
++const DEFAULT_NAME = 'xterm';
++const DESTROY_SOCKET_TIMEOUT_MS = 200;
++
++export class UnixTerminal extends Terminal {
++  protected _fd: number;
++  protected _pty: string;
++
++  protected _file: string;
++  protected _name: string;
++
++  protected _readable: boolean;
++  protected _writable: boolean;
++
++  private _boundClose: boolean;
++  private _emittedClose: boolean;
++  private _master: net.Socket;
++  private _slave: net.Socket;
++
++  public get master(): net.Socket { return this._master; }
++  public get slave(): net.Socket { return this._slave; }
++
++  constructor(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions) {
++    super(opt);
++
++    if (typeof args === 'string') {
++      throw new Error('args as a string is not supported on unix.');
++    }
++
++    // Initialize arguments
++    args = args || [];
++    file = file || DEFAULT_FILE;
++    opt = opt || {};
++    opt.env = opt.env || process.env;
++
++    this._cols = opt.cols || DEFAULT_COLS;
++    this._rows = opt.rows || DEFAULT_ROWS;
++    const uid = opt.uid || -1;
++    const gid = opt.gid || -1;
++    const env = assign({}, opt.env);
++
++    if (opt.env === process.env) {
++      this._sanitizeEnv(env);
++    }
++
++    const cwd = opt.cwd || process.cwd();
++    const name = opt.name || env.TERM || DEFAULT_NAME;
++    env.TERM = name;
++    const parsedEnv = this._parseEnv(env);
++
++    const encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
++
++    const onexit = (code: number, signal: number) => {
++      // XXX Sometimes a data event is emitted after exit. Wait til socket is
++      // destroyed.
++      if (!this._emittedClose) {
++        if (this._boundClose) {
++          return;
++        }
++        this._boundClose = true;
++        // From macOS High Sierra 10.13.2 sometimes the socket never gets
++        // closed. A timeout is applied here to avoid the terminal never being
++        // destroyed when this occurs.
++        let timeout = setTimeout(() => {
++          timeout = null;
++          // Destroying the socket now will cause the close event to fire
++          this._socket.destroy();
++        }, DESTROY_SOCKET_TIMEOUT_MS);
++        this.once('close', () => {
++          if (timeout !== null) {
++            clearTimeout(timeout);
++          }
++          this.emit('exit', code, signal);
++        });
++        return;
++      }
++      this.emit('exit', code, signal);
++    };
++
++    // fork
++    const term = pty.fork(file, args, parsedEnv, cwd, this._cols, this._rows, uid, gid, (encoding === 'utf8'), onexit);
++
++    this._socket = new PipeSocket(term.fd);
++    if (encoding !== null) {
++      this._socket.setEncoding(encoding);
++    }
++
++    // setup
++    this._socket.on('error', (err: any) => {
++      // NOTE: fs.ReadStream gets EAGAIN twice at first:
++      if (err.code) {
++        if (~err.code.indexOf('EAGAIN')) {
++          return;
++        }
++      }
++
++      // close
++      this._close();
++      // EIO on exit from fs.ReadStream:
++      if (!this._emittedClose) {
++        this._emittedClose = true;
++        this.emit('close');
++      }
++
++      // EIO, happens when someone closes our child process: the only process in
++      // the terminal.
++      // node < 0.6.14: errno 5
++      // node >= 0.6.14: read EIO
++      if (err.code) {
++        if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) {
++          return;
++        }
++      }
++
++      // throw anything else
++      if (this.listeners('error').length < 2) {
++        throw err;
++      }
++    });
++
++    this._pid = term.pid;
++    this._fd = term.fd;
++    this._pty = term.pty;
++
++    this._file = file;
++    this._name = name;
++
++    this._readable = true;
++    this._writable = true;
++
++    this._socket.on('close', () => {
++      if (this._emittedClose) {
++        return;
++      }
++      this._emittedClose = true;
++      this._close();
++      this.emit('close');
++    });
++
++    this._forwardEvents();
++  }
++
++  protected _write(data: string): void {
++    this._socket.write(data);
++  }
++
++  /**
++   * openpty
++   */
++
++  public static open(opt: IPtyOpenOptions): UnixTerminal {
++    const self: UnixTerminal = Object.create(UnixTerminal.prototype);
++    opt = opt || {};
++
++    if (arguments.length > 1) {
++      opt = {
++        cols: arguments[1],
++        rows: arguments[2]
++      };
++    }
++
++    const cols = opt.cols || DEFAULT_COLS;
++    const rows = opt.rows || DEFAULT_ROWS;
++    const encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
++
++    // open
++    const term: IUnixOpenProcess = pty.open(cols, rows);
++
++    self._master = new PipeSocket(<number>term.master);
++    if (encoding !== null) {
++        self._master.setEncoding(encoding);
++    }
++    self._master.resume();
++
++    self._slave = new PipeSocket(term.slave);
++    if (encoding !== null) {
++        self._slave.setEncoding(encoding);
++    }
++    self._slave.resume();
++
++    self._socket = self._master;
++    self._pid = null;
++    self._fd = term.master;
++    self._pty = term.pty;
++
++    self._file = process.argv[0] || 'node';
++    self._name = process.env.TERM || '';
++
++    self._readable = true;
++    self._writable = true;
++
++    self._socket.on('error', err => {
++      self._close();
++      if (self.listeners('error').length < 2) {
++        throw err;
++      }
++    });
++
++    self._socket.on('close', () => {
++      self._close();
++    });
++
++    return self;
++  }
++
++  public destroy(): void {
++    this._close();
++
++    // Need to close the read stream so node stops reading a dead file
++    // descriptor. Then we can safely SIGHUP the shell.
++    this._socket.once('close', () => {
++      this.kill('SIGHUP');
++    });
++
++    this._socket.destroy();
++  }
++
++  public kill(signal?: string): void {
++    try {
++      process.kill(this.pid, signal || 'SIGHUP');
++    } catch (e) { /* swallow */ }
++  }
++
++  /**
++   * Gets the name of the process.
++   */
++  public get process(): string {
++    return pty.process(this._fd, this._pty) || this._file;
++  }
++
++  /**
++   * TTY
++   */
++
++  public resize(cols: number, rows: number): void {
++    if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
++      throw new Error('resizing must be done using positive cols and rows');
++    }
++    pty.resize(this._fd, cols, rows);
++    this._cols = cols;
++    this._rows = rows;
++  }
++
++  private _sanitizeEnv(env: IProcessEnv): void {
++      // Make sure we didn't start our server from inside tmux.
++      delete env['TMUX'];
++      delete env['TMUX_PANE'];
++
++      // Make sure we didn't start our server from inside screen.
++      // http://web.mit.edu/gnu/doc/html/screen_20.html
++      delete env['STY'];
++      delete env['WINDOW'];
++
++      // Delete some variables that might confuse our terminal.
++      delete env['WINDOWID'];
++      delete env['TERMCAP'];
++      delete env['COLUMNS'];
++      delete env['LINES'];
++  }
++}
++
++/**
++ * Wraps net.Socket to force the handle type "PIPE" by temporarily overwriting
++ * tty_wrap.guessHandleType.
++ * See: https://github.com/chjj/pty.js/issues/103
++ */
++class PipeSocket extends net.Socket {
++  constructor(fd: number) {
++    const { Pipe, constants } = (<any>process).binding('pipe_wrap'); // tslint:disable-line
++    // @types/node has fd as string? https://github.com/DefinitelyTyped/DefinitelyTyped/pull/18275
++    const handle = new Pipe(constants.SOCKET);
++    handle.open(fd);
++    super(<any>{ handle });
++  }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..6306c8ba2f9de7a9cf8313dcac5dd0da21b0df01
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,9 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++export function assign(target: any, ...sources: any[]): any {
++  sources.forEach(source => Object.keys(source).forEach(key => target[key] = source[key]));
++  return target;
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4500f6ef0fc73eb1aa68a4af0d77402abaf69914
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,455 @@@
++/**
++ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ *
++ * pty.cc:
++ *   This file is responsible for starting processes
++ *   with pseudo-terminal file descriptors.
++ */
++
++// node versions lower than 10 define this as 0x502 which disables many of the definitions needed to compile
++#include <node_version.h>
++#if NODE_MODULE_VERSION <= 57
++  #define _WIN32_WINNT 0x600
++#endif
++
++#include <iostream>
++#include <nan.h>
++#include <Shlwapi.h> // PathCombine, PathIsRelative
++#include <sstream>
++#include <string>
++#include <vector>
++#include <Windows.h>
++#include <strsafe.h>
++#include "path_util.h"
++
++extern "C" void init(v8::Local<v8::Object>);
++
++// Taken from the RS5 Windows SDK, but redefined here in case we're targeting <= 17134
++#ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
++#define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE \
++  ProcThreadAttributeValue(22, FALSE, TRUE, FALSE)
++
++typedef VOID* HPCON;
++typedef HRESULT (__stdcall *PFNCREATEPSEUDOCONSOLE)(COORD c, HANDLE hIn, HANDLE hOut, DWORD dwFlags, HPCON* phpcon);
++typedef HRESULT (__stdcall *PFNRESIZEPSEUDOCONSOLE)(HPCON hpc, COORD newSize);
++typedef void (__stdcall *PFNCLOSEPSEUDOCONSOLE)(HPCON hpc);
++
++#endif
++
++struct pty_baton {
++  int id;
++  HANDLE hIn;
++  HANDLE hOut;
++  HPCON hpc;
++
++  HANDLE hShell;
++  HANDLE hWait;
++  Nan::Callback cb;
++  uv_async_t async;
++  uv_thread_t tid;
++
++  pty_baton(int _id, HANDLE _hIn, HANDLE _hOut, HPCON _hpc) : id(_id), hIn(_hIn), hOut(_hOut), hpc(_hpc) {};
++};
++
++static std::vector<pty_baton*> ptyHandles;
++static volatile LONG ptyCounter;
++
++static pty_baton* get_pty_baton(int id) {
++  for (size_t i = 0; i < ptyHandles.size(); ++i) {
++    pty_baton* ptyHandle = ptyHandles[i];
++    if (ptyHandle->id == id) {
++      return ptyHandle;
++    }
++  }
++  return nullptr;
++}
++
++template <typename T>
++std::vector<T> vectorFromString(const std::basic_string<T> &str) {
++    return std::vector<T>(str.begin(), str.end());
++}
++
++void throwNanError(const Nan::FunctionCallbackInfo<v8::Value>* info, const char* text, const bool getLastError) {
++  std::stringstream errorText;
++  errorText << text;
++  if (getLastError) {
++    errorText << ", error code: " << GetLastError();
++  }
++  Nan::ThrowError(errorText.str().c_str());
++  (*info).GetReturnValue().SetUndefined();
++}
++
++// Returns a new server named pipe.  It has not yet been connected.
++bool createDataServerPipe(bool write,
++                          std::wstring kind,
++                          HANDLE* hServer,
++                          std::wstring &name,
++                          const std::wstring &pipeName)
++{
++  *hServer = INVALID_HANDLE_VALUE;
++
++  name = L"\\\\.\\pipe\\" + pipeName + L"-" + kind;
++
++  const DWORD winOpenMode =  PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE/*  | FILE_FLAG_OVERLAPPED */;
++
++  SECURITY_ATTRIBUTES sa = {};
++  sa.nLength = sizeof(sa);
++
++  *hServer = CreateNamedPipeW(
++      name.c_str(),
++      /*dwOpenMode=*/winOpenMode,
++      /*dwPipeMode=*/PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
++      /*nMaxInstances=*/1,
++      /*nOutBufferSize=*/0,
++      /*nInBufferSize=*/0,
++      /*nDefaultTimeOut=*/30000,
++      &sa);
++
++  return *hServer != INVALID_HANDLE_VALUE;
++}
++
++HRESULT CreateNamedPipesAndPseudoConsole(COORD size,
++                                         DWORD dwFlags,
++                                         HANDLE *phInput,
++                                         HANDLE *phOutput,
++                                         HPCON* phPC,
++                                         std::wstring& inName,
++                                         std::wstring& outName,
++                                         const std::wstring& pipeName)
++{
++  HANDLE hLibrary = LoadLibraryExW(L"kernel32.dll", 0, 0);
++  bool fLoadedDll = hLibrary != nullptr;
++  if (fLoadedDll)
++  {
++    PFNCREATEPSEUDOCONSOLE const pfnCreate = (PFNCREATEPSEUDOCONSOLE)GetProcAddress((HMODULE)hLibrary, "CreatePseudoConsole");
++    if (pfnCreate)
++    {
++      if (phPC == NULL || phInput == NULL || phOutput == NULL)
++      {
++        return E_INVALIDARG;
++      }
++
++      bool success = createDataServerPipe(true, L"in", phInput, inName, pipeName);
++      if (!success)
++      {
++        return HRESULT_FROM_WIN32(GetLastError());
++      }
++      success = createDataServerPipe(false, L"out", phOutput, outName, pipeName);
++      if (!success)
++      {
++        return HRESULT_FROM_WIN32(GetLastError());
++      }
++      return pfnCreate(size, *phInput, *phOutput, dwFlags, phPC);
++    }
++    else
++    {
++      // Failed to find CreatePseudoConsole in kernel32. This is likely because
++      //    the user is not running a build of Windows that supports that API.
++      //    We should fall back to winpty in this case.
++      return HRESULT_FROM_WIN32(GetLastError());
++    }
++  }
++
++  // Failed to find  kernel32. This is realy unlikely - honestly no idea how
++  //    this is even possible to hit. But if it does happen, fall back to winpty.
++  return HRESULT_FROM_WIN32(GetLastError());
++}
++
++static NAN_METHOD(PtyStartProcess) {
++  Nan::HandleScope scope;
++
++  v8::Local<v8::Object> marshal;
++  std::wstring inName, outName;
++  BOOL fSuccess = FALSE;
++  std::unique_ptr<wchar_t[]> mutableCommandline;
++  PROCESS_INFORMATION _piClient{};
++
++  if (info.Length() != 6 ||
++      !info[0]->IsString() ||
++      !info[1]->IsNumber() ||
++      !info[2]->IsNumber() ||
++      !info[3]->IsBoolean() ||
++      !info[4]->IsString() ||
++      !info[5]->IsBoolean()) {
++    Nan::ThrowError("Usage: pty.startProcess(file, cols, rows, debug, pipeName, inheritCursor)");
++    return;
++  }
++
++  const std::wstring filename(path_util::to_wstring(Nan::Utf8String(info[0])));
++  const SHORT cols = info[1]->Uint32Value(Nan::GetCurrentContext()).FromJust();
++  const SHORT rows = info[2]->Uint32Value(Nan::GetCurrentContext()).FromJust();
++  const bool debug = Nan::To<bool>(info[3]).FromJust();
++  const std::wstring pipeName(path_util::to_wstring(Nan::Utf8String(info[4])));
++  const bool inheritCursor = Nan::To<bool>(info[5]).FromJust();
++
++  // use environment 'Path' variable to determine location of
++  // the relative path that we have recieved (e.g cmd.exe)
++  std::wstring shellpath;
++  if (::PathIsRelativeW(filename.c_str())) {
++    shellpath = path_util::get_shell_path(filename.c_str());
++  } else {
++    shellpath = filename;
++  }
++
++  std::string shellpath_(shellpath.begin(), shellpath.end());
++
++  if (shellpath.empty() || !path_util::file_exists(shellpath)) {
++    std::stringstream why;
++    why << "File not found: " << shellpath_;
++    Nan::ThrowError(why.str().c_str());
++    return;
++  }
++
++  HANDLE hIn, hOut;
++  HPCON hpc;
++  HRESULT hr = CreateNamedPipesAndPseudoConsole({cols, rows}, inheritCursor ? 1/*PSEUDOCONSOLE_INHERIT_CURSOR*/ : 0, &hIn, &hOut, &hpc, inName, outName, pipeName);
++
++  // Restore default handling of ctrl+c
++  SetConsoleCtrlHandler(NULL, FALSE);
++
++  // Set return values
++  marshal = Nan::New<v8::Object>();
++
++  if (SUCCEEDED(hr)) {
++    // We were able to instantiate a conpty
++    const int ptyId = InterlockedIncrement(&ptyCounter);
++    Nan::Set(marshal, Nan::New<v8::String>("pty").ToLocalChecked(), Nan::New<v8::Number>(ptyId));
++    ptyHandles.insert(ptyHandles.end(), new pty_baton(ptyId, hIn, hOut, hpc));
++  } else {
++    Nan::ThrowError("Cannot launch conpty");
++    return;
++  }
++
++  Nan::Set(marshal, Nan::New<v8::String>("fd").ToLocalChecked(), Nan::New<v8::Number>(-1));
++  {
++    std::string coninPipeNameStr(inName.begin(), inName.end());
++    Nan::Set(marshal, Nan::New<v8::String>("conin").ToLocalChecked(), Nan::New<v8::String>(coninPipeNameStr).ToLocalChecked());
++
++    std::string conoutPipeNameStr(outName.begin(), outName.end());
++    Nan::Set(marshal, Nan::New<v8::String>("conout").ToLocalChecked(), Nan::New<v8::String>(conoutPipeNameStr).ToLocalChecked());
++  }
++  info.GetReturnValue().Set(marshal);
++}
++
++VOID CALLBACK OnProcessExitWinEvent(
++    _In_ PVOID context,
++    _In_ BOOLEAN TimerOrWaitFired) {
++  pty_baton *baton = static_cast<pty_baton*>(context);
++
++  // Fire OnProcessExit
++  uv_async_send(&baton->async);
++}
++
++static void OnProcessExit(uv_async_t *async) {
++  Nan::HandleScope scope;
++  pty_baton *baton = static_cast<pty_baton*>(async->data);
++
++  UnregisterWait(baton->hWait);
++
++  // Get exit code
++  DWORD exitCode = 0;
++  GetExitCodeProcess(baton->hShell, &exitCode);
++
++  // Call function
++  v8::Local<v8::Value> args[1] = {
++    Nan::New<v8::Number>(exitCode)
++  };
++
++  Nan::AsyncResource asyncResource("node-pty.callback");
++  baton->cb.Call(1, args, &asyncResource);
++  // Clean up
++  baton->cb.Reset();
++}
++
++static NAN_METHOD(PtyConnect) {
++  Nan::HandleScope scope;
++
++  // If we're working with conpty's we need to call ConnectNamedPipe here AFTER
++  //    the Socket has attempted to connect to the other end, then actually
++  //    spawn the process here.
++
++  std::stringstream errorText;
++  BOOL fSuccess = FALSE;
++
++  if (info.Length() != 5 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsString() ||
++      !info[2]->IsString() ||
++      !info[3]->IsArray() ||
++      !info[4]->IsFunction()) {
++    Nan::ThrowError("Usage: pty.connect(id, cmdline, cwd, env, exitCallback)");
++    return;
++  }
++
++  const int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  const std::wstring cmdline(path_util::to_wstring(Nan::Utf8String(info[1])));
++  const std::wstring cwd(path_util::to_wstring(Nan::Utf8String(info[2])));
++  const v8::Local<v8::Array> envValues = info[3].As<v8::Array>();
++  const v8::Local<v8::Function> exitCallback = v8::Local<v8::Function>::Cast(info[4]);
++
++  // Prepare command line
++  std::unique_ptr<wchar_t[]> mutableCommandline = std::make_unique<wchar_t[]>(cmdline.length() + 1);
++  HRESULT hr = StringCchCopyW(mutableCommandline.get(), cmdline.length() + 1, cmdline.c_str());
++
++  // Prepare cwd
++  std::unique_ptr<wchar_t[]> mutableCwd = std::make_unique<wchar_t[]>(cwd.length() + 1);
++  hr = StringCchCopyW(mutableCwd.get(), cwd.length() + 1, cwd.c_str());
++
++  // Prepare environment
++  std::wstring env;
++  if (!envValues.IsEmpty()) {
++    std::wstringstream envBlock;
++    for(uint32_t i = 0; i < envValues->Length(); i++) {
++      std::wstring envValue(path_util::to_wstring(Nan::Utf8String(Nan::Get(envValues, i).ToLocalChecked())));
++      envBlock << envValue << L'\0';
++    }
++    envBlock << L'\0';
++    env = envBlock.str();
++  }
++  auto envV = vectorFromString(env);
++  LPWSTR envArg = envV.empty() ? nullptr : envV.data();
++
++  // Fetch pty handle from ID and start process
++  pty_baton* handle = get_pty_baton(id);
++
++  BOOL success = ConnectNamedPipe(handle->hIn, nullptr);
++  success = ConnectNamedPipe(handle->hOut, nullptr);
++
++  // Attach the pseudoconsole to the client application we're creating
++  STARTUPINFOEXW siEx{0};
++  siEx.StartupInfo.cb = sizeof(STARTUPINFOEXW);
++  siEx.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
++  siEx.StartupInfo.hStdError = nullptr;
++  siEx.StartupInfo.hStdInput = nullptr;
++  siEx.StartupInfo.hStdOutput = nullptr;
++
++  SIZE_T size = 0;
++  InitializeProcThreadAttributeList(NULL, 1, 0, &size);
++  BYTE *attrList = new BYTE[size];
++  siEx.lpAttributeList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrList);
++
++  fSuccess = InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, &size);
++  if (!fSuccess) {
++    return throwNanError(&info, "InitializeProcThreadAttributeList failed", true);
++  }
++  fSuccess = UpdateProcThreadAttribute(siEx.lpAttributeList,
++                                       0,
++                                       PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
++                                       handle->hpc,
++                                       sizeof(HPCON),
++                                       NULL,
++                                       NULL);
++  if (!fSuccess) {
++    return throwNanError(&info, "UpdateProcThreadAttribute failed", true);
++  }
++
++  PROCESS_INFORMATION piClient{};
++  fSuccess = !!CreateProcessW(
++      nullptr,
++      mutableCommandline.get(),
++      nullptr,                      // lpProcessAttributes
++      nullptr,                      // lpThreadAttributes
++      false,                        // bInheritHandles VERY IMPORTANT that this is false
++      EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT, // dwCreationFlags
++      envArg,                       // lpEnvironment
++      mutableCwd.get(),             // lpCurrentDirectory
++      &siEx.StartupInfo,            // lpStartupInfo
++      &piClient                     // lpProcessInformation
++  );
++  if (!fSuccess) {
++    return throwNanError(&info, "Cannot create process", true);
++  }
++
++  // Update handle
++  handle->hShell = piClient.hProcess;
++  handle->cb.Reset(exitCallback);
++  handle->async.data = handle;
++
++  // Setup OnProcessExit callback
++  uv_async_init(uv_default_loop(), &handle->async, OnProcessExit);
++
++  // Setup Windows wait for process exit event
++  RegisterWaitForSingleObject(&handle->hWait, piClient.hProcess, OnProcessExitWinEvent, (PVOID)handle, INFINITE, WT_EXECUTEONLYONCE);
++
++  // Return
++  v8::Local<v8::Object> marshal = Nan::New<v8::Object>();
++  Nan::Set(marshal, Nan::New<v8::String>("pid").ToLocalChecked(), Nan::New<v8::Number>(piClient.dwProcessId));
++  info.GetReturnValue().Set(marshal);
++}
++
++static NAN_METHOD(PtyResize) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 3 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsNumber() ||
++      !info[2]->IsNumber()) {
++    Nan::ThrowError("Usage: pty.resize(id, cols, rows)");
++    return;
++  }
++
++  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  SHORT cols = info[1]->Uint32Value(Nan::GetCurrentContext()).FromJust();
++  SHORT rows = info[2]->Uint32Value(Nan::GetCurrentContext()).FromJust();
++
++  const pty_baton* handle = get_pty_baton(id);
++
++  HANDLE hLibrary = LoadLibraryExW(L"kernel32.dll", 0, 0);
++  bool fLoadedDll = hLibrary != nullptr;
++  if (fLoadedDll)
++  {
++    PFNRESIZEPSEUDOCONSOLE const pfnResizePseudoConsole = (PFNRESIZEPSEUDOCONSOLE)GetProcAddress((HMODULE)hLibrary, "ResizePseudoConsole");
++    if (pfnResizePseudoConsole)
++    {
++      COORD size = {cols, rows};
++      pfnResizePseudoConsole(handle->hpc, size);
++    }
++  }
++
++  return info.GetReturnValue().SetUndefined();
++}
++
++static NAN_METHOD(PtyKill) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 1 ||
++      !info[0]->IsNumber()) {
++    Nan::ThrowError("Usage: pty.kill(id)");
++    return;
++  }
++
++  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
++
++  const pty_baton* handle = get_pty_baton(id);
++
++  HANDLE hLibrary = LoadLibraryExW(L"kernel32.dll", 0, 0);
++  bool fLoadedDll = hLibrary != nullptr;
++  if (fLoadedDll)
++  {
++    PFNCLOSEPSEUDOCONSOLE const pfnClosePseudoConsole = (PFNCLOSEPSEUDOCONSOLE)GetProcAddress((HMODULE)hLibrary, "ClosePseudoConsole");
++    if (pfnClosePseudoConsole)
++    {
++      pfnClosePseudoConsole(handle->hpc);
++    }
++  }
++
++  CloseHandle(handle->hShell);
++
++  return info.GetReturnValue().SetUndefined();
++}
++
++/**
++* Init
++*/
++
++extern "C" void init(v8::Local<v8::Object> target) {
++  Nan::HandleScope scope;
++  Nan::SetMethod(target, "startProcess", PtyStartProcess);
++  Nan::SetMethod(target, "connect", PtyConnect);
++  Nan::SetMethod(target, "resize", PtyResize);
++  Nan::SetMethod(target, "kill", PtyKill);
++};
++
++NODE_MODULE(pty, init);
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..be135ba024a73547ac9702bf7cb22ae649c60dd3
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,43 @@@
++/**
++ * Copyright (c) 2019, Microsoft Corporation (MIT License).
++ */
++
++#include <nan.h>
++#include <windows.h>
++
++static NAN_METHOD(ApiConsoleProcessList) {
++  if (info.Length() != 1 ||
++      !info[0]->IsNumber()) {
++    Nan::ThrowError("Usage: getConsoleProcessList(shellPid)");
++    return;
++  }
++
++  const SHORT pid = info[0]->Uint32Value(Nan::GetCurrentContext()).FromJust();
++
++  if (!FreeConsole()) {
++    Nan::ThrowError("FreeConsole failed");
++  }
++  if (!AttachConsole(pid)) {
++    Nan::ThrowError("AttachConsole failed");
++  }
++  auto processList = std::vector<DWORD>(64);
++  auto processCount = GetConsoleProcessList(&processList[0], processList.size());
++  if (processList.size() < processCount) {
++      processList.resize(processCount);
++      processCount = GetConsoleProcessList(&processList[0], processList.size());
++  }
++  FreeConsole();
++
++  v8::Local<v8::Array> result = Nan::New<v8::Array>();
++  for (DWORD i = 0; i < processCount; i++) {
++    Nan::Set(result, i, Nan::New<v8::Number>(processList[i]));
++  }
++  info.GetReturnValue().Set(result);
++}
++
++extern "C" void init(v8::Local<v8::Object> target) {
++  Nan::HandleScope scope;
++  Nan::SetMethod(target, "getConsoleProcessList", ApiConsoleProcessList);
++};
++
++NODE_MODULE(pty, init);
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..4e69f3091a45fddb3c2b590a5ac27d68273e9afa
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,73 @@@
++/**
++ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++#include <nan.h>
++#include <Shlwapi.h> // PathCombine
++
++#include "path_util.h"
++
++namespace path_util {
++
++const wchar_t* to_wstring(const Nan::Utf8String& str) {
++  const char *bytes = *str;
++  unsigned int sizeOfStr = MultiByteToWideChar(CP_UTF8, 0, bytes, -1, NULL, 0);
++  wchar_t *output = new wchar_t[sizeOfStr];
++  MultiByteToWideChar(CP_UTF8, 0, bytes, -1, output, sizeOfStr);
++  return output;
++}
++
++bool file_exists(std::wstring filename) {
++  DWORD attr = ::GetFileAttributesW(filename.c_str());
++  if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
++    return false;
++  }
++  return true;
++}
++
++// cmd.exe -> C:\Windows\system32\cmd.exe
++std::wstring get_shell_path(std::wstring filename) {
++  std::wstring shellpath;
++
++  if (file_exists(filename)) {
++    return shellpath;
++  }
++
++  wchar_t buffer_[MAX_ENV];
++  int read = ::GetEnvironmentVariableW(L"Path", buffer_, MAX_ENV);
++  if (!read) {
++    return shellpath;
++  }
++
++  std::wstring delimiter = L";";
++  size_t pos = 0;
++  std::vector<std::wstring> paths;
++  std::wstring buffer(buffer_);
++  while ((pos = buffer.find(delimiter)) != std::wstring::npos) {
++    paths.push_back(buffer.substr(0, pos));
++    buffer.erase(0, pos + delimiter.length());
++  }
++
++  const wchar_t *filename_ = filename.c_str();
++
++  for (int i = 0; i < paths.size(); ++i) {
++    std::wstring path = paths[i];
++    wchar_t searchPath[MAX_PATH];
++    ::PathCombineW(searchPath, const_cast<wchar_t*>(path.c_str()), filename_);
++
++    if (searchPath == NULL) {
++      continue;
++    }
++
++    if (file_exists(searchPath)) {
++      shellpath = searchPath;
++      break;
++    }
++  }
++
++  return shellpath;
++}
++
++}  // namespace path_util
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..8dd58d25e0579219923774de48522ecfd0039a99
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,22 @@@
++/**
++ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++#ifndef NODE_PTY_PATH_UTIL_H_
++#define NODE_PTY_PATH_UTIL_H_
++
++#include <nan.h>
++
++#define MAX_ENV 65536
++
++namespace path_util {
++
++const wchar_t* to_wstring(const Nan::Utf8String& str);
++bool file_exists(std::wstring filename);
++std::wstring get_shell_path(std::wstring filename);
++
++}  // namespace path_util
++
++#endif  // NODE_PTY_PATH_UTIL_H_
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b054dee2194226a823f5c98befdecf06cda2e5dd
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,312 @@@
++/**
++ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ *
++ * pty.cc:
++ *   This file is responsible for starting processes
++ *   with pseudo-terminal file descriptors.
++ */
++
++#include <iostream>
++#include <nan.h>
++#include <Shlwapi.h> // PathCombine, PathIsRelative
++#include <sstream>
++#include <stdlib.h>
++#include <string.h>
++#include <string>
++#include <vector>
++#include <winpty.h>
++
++#include "path_util.h"
++
++/**
++* Misc
++*/
++extern "C" void init(v8::Local<v8::Object>);
++
++#define WINPTY_DBG_VARIABLE TEXT("WINPTYDBG")
++
++/**
++* winpty
++*/
++static std::vector<winpty_t *> ptyHandles;
++static volatile LONG ptyCounter;
++
++/**
++* Helpers
++*/
++
++static winpty_t *get_pipe_handle(int handle) {
++  for (size_t i = 0; i < ptyHandles.size(); ++i) {
++    winpty_t *ptyHandle = ptyHandles[i];
++    int current = (int)winpty_agent_process(ptyHandle);
++    if (current == handle) {
++      return ptyHandle;
++    }
++  }
++  return nullptr;
++}
++
++static bool remove_pipe_handle(int handle) {
++  for (size_t i = 0; i < ptyHandles.size(); ++i) {
++    winpty_t *ptyHandle = ptyHandles[i];
++    if ((int)winpty_agent_process(ptyHandle) == handle) {
++      winpty_free(ptyHandle);
++      ptyHandles.erase(ptyHandles.begin() + i);
++      ptyHandle = nullptr;
++      return true;
++    }
++  }
++  return false;
++}
++
++void throw_winpty_error(const char *generalMsg, winpty_error_ptr_t error_ptr) {
++  std::stringstream why;
++  std::wstring msg(winpty_error_msg(error_ptr));
++  std::string msg_(msg.begin(), msg.end());
++  why << generalMsg << ": " << msg_;
++  Nan::ThrowError(why.str().c_str());
++  winpty_error_free(error_ptr);
++}
++
++static NAN_METHOD(PtyGetExitCode) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 1 ||
++      !info[0]->IsNumber()) {
++    Nan::ThrowError("Usage: pty.getExitCode(pidHandle)");
++    return;
++  }
++
++  DWORD exitCode = 0;
++  GetExitCodeProcess((HANDLE)info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust(), &exitCode);
++
++  info.GetReturnValue().Set(Nan::New<v8::Number>(exitCode));
++}
++
++static NAN_METHOD(PtyGetProcessList) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 1 ||
++      !info[0]->IsNumber()) {
++    Nan::ThrowError("Usage: pty.getProcessList(pid)");
++    return;
++  }
++
++  int pid = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
++
++  winpty_t *pc = get_pipe_handle(pid);
++  if (pc == nullptr) {
++    info.GetReturnValue().Set(Nan::New<v8::Array>(0));
++    return;
++  }
++  int processList[64];
++  const int processCount = 64;
++  int actualCount = winpty_get_console_process_list(pc, processList, processCount, nullptr);
++
++  v8::Local<v8::Array> result = Nan::New<v8::Array>(actualCount);
++  for (uint32_t i = 0; i < actualCount; i++) {
++    Nan::Set(result, i, Nan::New<v8::Number>(processList[i]));
++  }
++  info.GetReturnValue().Set(result);
++}
++
++static NAN_METHOD(PtyStartProcess) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 7 ||
++      !info[0]->IsString() ||
++      !info[1]->IsString() ||
++      !info[2]->IsArray() ||
++      !info[3]->IsString() ||
++      !info[4]->IsNumber() ||
++      !info[5]->IsNumber() ||
++      !info[6]->IsBoolean()) {
++    Nan::ThrowError("Usage: pty.startProcess(file, cmdline, env, cwd, cols, rows, debug)");
++    return;
++  }
++
++  std::stringstream why;
++
++  const wchar_t *filename = path_util::to_wstring(Nan::Utf8String(info[0]));
++  const wchar_t *cmdline = path_util::to_wstring(Nan::Utf8String(info[1]));
++  const wchar_t *cwd = path_util::to_wstring(Nan::Utf8String(info[3]));
++
++  // create environment block
++  std::wstring env;
++  const v8::Local<v8::Array> envValues = v8::Local<v8::Array>::Cast(info[2]);
++  if (!envValues.IsEmpty()) {
++
++    std::wstringstream envBlock;
++
++    for(uint32_t i = 0; i < envValues->Length(); i++) {
++      std::wstring envValue(path_util::to_wstring(Nan::Utf8String(Nan::Get(envValues, i).ToLocalChecked())));
++      envBlock << envValue << L'\0';
++    }
++
++    env = envBlock.str();
++  }
++
++  // use environment 'Path' variable to determine location of
++  // the relative path that we have recieved (e.g cmd.exe)
++  std::wstring shellpath;
++  if (::PathIsRelativeW(filename)) {
++    shellpath = path_util::get_shell_path(filename);
++  } else {
++    shellpath = filename;
++  }
++
++  std::string shellpath_(shellpath.begin(), shellpath.end());
++
++  if (shellpath.empty() || !path_util::file_exists(shellpath)) {
++    why << "File not found: " << shellpath_;
++    Nan::ThrowError(why.str().c_str());
++    goto cleanup;
++  }
++
++  int cols = info[4]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  int rows = info[5]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  bool debug = Nan::To<bool>(info[6]).FromJust();
++
++  // Enable/disable debugging
++  SetEnvironmentVariable(WINPTY_DBG_VARIABLE, debug ? "1" : NULL); // NULL = deletes variable
++
++  // Create winpty config
++  winpty_error_ptr_t error_ptr = nullptr;
++  winpty_config_t* winpty_config = winpty_config_new(0, &error_ptr);
++  if (winpty_config == nullptr) {
++    throw_winpty_error("Error creating WinPTY config", error_ptr);
++    goto cleanup;
++  }
++  winpty_error_free(error_ptr);
++
++  // Set pty size on config
++  winpty_config_set_initial_size(winpty_config, cols, rows);
++
++  // Start the pty agent
++  winpty_t *pc = winpty_open(winpty_config, &error_ptr);
++  winpty_config_free(winpty_config);
++  if (pc == nullptr) {
++    throw_winpty_error("Error launching WinPTY agent", error_ptr);
++    goto cleanup;
++  }
++  winpty_error_free(error_ptr);
++
++  // Save pty struct for later use
++  ptyHandles.insert(ptyHandles.end(), pc);
++
++  // Create winpty spawn config
++  winpty_spawn_config_t* config = winpty_spawn_config_new(WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN, shellpath.c_str(), cmdline, cwd, env.c_str(), &error_ptr);
++  if (config == nullptr) {
++    throw_winpty_error("Error creating WinPTY spawn config", error_ptr);
++    goto cleanup;
++  }
++  winpty_error_free(error_ptr);
++
++  // Spawn the new process
++  HANDLE handle = nullptr;
++  BOOL spawnSuccess = winpty_spawn(pc, config, &handle, nullptr, nullptr, &error_ptr);
++  winpty_spawn_config_free(config);
++  if (!spawnSuccess) {
++    throw_winpty_error("Unable to start terminal process", error_ptr);
++    goto cleanup;
++  }
++  winpty_error_free(error_ptr);
++
++  // Set return values
++  v8::Local<v8::Object> marshal = Nan::New<v8::Object>();
++  Nan::Set(marshal, Nan::New<v8::String>("innerPid").ToLocalChecked(), Nan::New<v8::Number>((int)GetProcessId(handle)));
++  Nan::Set(marshal, Nan::New<v8::String>("innerPidHandle").ToLocalChecked(), Nan::New<v8::Number>((int)handle));
++  Nan::Set(marshal, Nan::New<v8::String>("pid").ToLocalChecked(), Nan::New<v8::Number>((int)winpty_agent_process(pc)));
++  Nan::Set(marshal, Nan::New<v8::String>("pty").ToLocalChecked(), Nan::New<v8::Number>(InterlockedIncrement(&ptyCounter)));
++  Nan::Set(marshal, Nan::New<v8::String>("fd").ToLocalChecked(), Nan::New<v8::Number>(-1));
++  {
++    LPCWSTR coninPipeName = winpty_conin_name(pc);
++    std::wstring coninPipeNameWStr(coninPipeName);
++    std::string coninPipeNameStr(coninPipeNameWStr.begin(), coninPipeNameWStr.end());
++    Nan::Set(marshal, Nan::New<v8::String>("conin").ToLocalChecked(), Nan::New<v8::String>(coninPipeNameStr).ToLocalChecked());
++    LPCWSTR conoutPipeName = winpty_conout_name(pc);
++    std::wstring conoutPipeNameWStr(conoutPipeName);
++    std::string conoutPipeNameStr(conoutPipeNameWStr.begin(), conoutPipeNameWStr.end());
++    Nan::Set(marshal, Nan::New<v8::String>("conout").ToLocalChecked(), Nan::New<v8::String>(conoutPipeNameStr).ToLocalChecked());
++  }
++  info.GetReturnValue().Set(marshal);
++
++  goto cleanup;
++
++cleanup:
++  delete filename;
++  delete cmdline;
++  delete cwd;
++}
++
++static NAN_METHOD(PtyResize) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 3 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsNumber() ||
++      !info[2]->IsNumber()) {
++    Nan::ThrowError("Usage: pty.resize(pid, cols, rows)");
++    return;
++  }
++
++  int handle = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  int cols = info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  int rows = info[2]->Int32Value(Nan::GetCurrentContext()).FromJust();
++
++  winpty_t *pc = get_pipe_handle(handle);
++
++  if (pc == nullptr) {
++    Nan::ThrowError("The pty doesn't appear to exist");
++    return;
++  }
++  BOOL success = winpty_set_size(pc, cols, rows, nullptr);
++  if (!success) {
++    Nan::ThrowError("The pty could not be resized");
++    return;
++  }
++
++  return info.GetReturnValue().SetUndefined();
++}
++
++static NAN_METHOD(PtyKill) {
++  Nan::HandleScope scope;
++
++  if (info.Length() != 2 ||
++      !info[0]->IsNumber() ||
++      !info[1]->IsNumber()) {
++    Nan::ThrowError("Usage: pty.kill(pid, innerPidHandle)");
++    return;
++  }
++
++  int handle = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
++  HANDLE innerPidHandle = (HANDLE)info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();
++
++  winpty_t *pc = get_pipe_handle(handle);
++  if (pc == nullptr) {
++    Nan::ThrowError("Pty seems to have been killed already");
++    return;
++  }
++
++  assert(remove_pipe_handle(handle));
++  CloseHandle(innerPidHandle);
++
++  return info.GetReturnValue().SetUndefined();
++}
++
++/**
++* Init
++*/
++
++extern "C" void init(v8::Local<v8::Object> target) {
++  Nan::HandleScope scope;
++  Nan::SetMethod(target, "startProcess", PtyStartProcess);
++  Nan::SetMethod(target, "resize", PtyResize);
++  Nan::SetMethod(target, "kill", PtyKill);
++  Nan::SetMethod(target, "getExitCode", PtyGetExitCode);
++  Nan::SetMethod(target, "getProcessList", PtyGetProcessList);
++};
++
++NODE_MODULE(pty, init);
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..dc2104b34fd396722a9e30821ff0b7dea18b4295
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,94 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import * as assert from 'assert';
++import { argsToCommandLine } from './windowsPtyAgent';
++
++function check(file: string, args: string | string[], expected: string): void {
++  assert.equal(argsToCommandLine(file, args), expected);
++}
++
++if (process.platform === 'win32') {
++  describe('argsToCommandLine', () => {
++    describe('Plain strings', () => {
++      it('doesn\'t quote plain string', () => {
++        check('asdf', [], 'asdf');
++      });
++      it('doesn\'t escape backslashes', () => {
++        check('\\asdf\\qwer\\', [], '\\asdf\\qwer\\');
++      });
++      it('doesn\'t escape multiple backslashes', () => {
++        check('asdf\\\\qwer', [], 'asdf\\\\qwer');
++      });
++      it('adds backslashes before quotes', () => {
++        check('"asdf"qwer"', [], '\\"asdf\\"qwer\\"');
++      });
++      it('escapes backslashes before quotes', () => {
++        check('asdf\\"qwer', [], 'asdf\\\\\\"qwer');
++      });
++    });
++
++    describe('Quoted strings', () => {
++      it('quotes string with spaces', () => {
++        check('asdf qwer', [], '"asdf qwer"');
++      });
++      it('quotes empty string', () => {
++        check('', [], '""');
++      });
++      it('quotes string with tabs', () => {
++        check('asdf\tqwer', [], '"asdf\tqwer"');
++      });
++      it('escapes only the last backslash', () => {
++        check('\\asdf \\qwer\\', [], '"\\asdf \\qwer\\\\"');
++      });
++      it('doesn\'t escape multiple backslashes', () => {
++        check('asdf \\\\qwer', [], '"asdf \\\\qwer"');
++      });
++      it('escapes backslashes before quotes', () => {
++        check('asdf \\"qwer', [], '"asdf \\\\\\"qwer"');
++      });
++      it('escapes multiple backslashes at the end', () => {
++        check('asdf qwer\\\\', [], '"asdf qwer\\\\\\\\"');
++      });
++    });
++
++    describe('Multiple arguments', () => {
++      it('joins arguments with spaces', () => {
++        check('asdf', ['qwer zxcv', '', '"'], 'asdf "qwer zxcv" "" \\"');
++      });
++      it('array argument all in quotes', () => {
++        check('asdf', ['"surounded by quotes"'], 'asdf \\"surounded by quotes\\"');
++      });
++      it('array argument quotes in the middle', () => {
++        check('asdf', ['quotes "in the" middle'], 'asdf "quotes \\"in the\\" middle"');
++      });
++      it('array argument quotes near start', () => {
++        check('asdf', ['"quotes" near start'], 'asdf "\\"quotes\\" near start"');
++      });
++      it('array argument quotes near end', () => {
++        check('asdf', ['quotes "near end"'], 'asdf "quotes \\"near end\\""');
++      });
++    });
++
++    describe('Args as CommandLine', () => {
++      it('should handle empty string', () => {
++        check('file', '', 'file');
++      });
++      it('should not change args', () => {
++        check('file', 'foo bar baz', 'file foo bar baz');
++        check('file', 'foo \\ba"r \baz', 'file foo \\ba"r \baz');
++      });
++    });
++
++    describe('Real-world cases', () => {
++      it('quotes within quotes', () => {
++        check('cmd.exe', ['/c', 'powershell -noexit -command \'Set-location \"C:\\user\"\''], 'cmd.exe /c "powershell -noexit -command \'Set-location \\\"C:\\user\\"\'"');
++      });
++      it('space within quotes', () => {
++        check('cmd.exe', ['/k', '"C:\\Users\\alros\\Desktop\\test script.bat"'], 'cmd.exe /k \\"C:\\Users\\alros\\Desktop\\test script.bat\\"');
++      });
++    });
++  });
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..cf8b65db61edb88f8b0ee78be5ca38e7b8f65e59
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,313 @@@
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import * as os from 'os';
++import * as path from 'path';
++import { Socket } from 'net';
++import { ArgvOrCommandLine } from './types';
++import { fork } from 'child_process';
++
++let conptyNative: IConptyNative;
++let winptyNative: IWinptyNative;
++
++/**
++ * The amount of time to wait for additional data after the conpty shell process has exited before
++ * shutting down the socket. The timer will be reset if a new data event comes in after the timer
++ * has started.
++ */
++const FLUSH_DATA_INTERVAL = 20;
++
++/**
++ * This agent sits between the WindowsTerminal class and provides a common interface for both conpty
++ * and winpty.
++ */
++export class WindowsPtyAgent {
++  private _inSocket: Socket;
++  private _outSocket: Socket;
++  private _pid: number;
++  private _innerPid: number;
++  private _innerPidHandle: number;
++  private _closeTimeout: NodeJS.Timer;
++  private _exitCode: number | undefined;
++
++  private _fd: any;
++  private _pty: number;
++  private _ptyNative: IConptyNative | IWinptyNative;
++
++  public get inSocket(): Socket { return this._inSocket; }
++  public get outSocket(): Socket { return this._outSocket; }
++  public get fd(): any { return this._fd; }
++  public get innerPid(): number { return this._innerPid; }
++  public get pty(): number { return this._pty; }
++
++  constructor(
++    file: string,
++    args: ArgvOrCommandLine,
++    env: string[],
++    cwd: string,
++    cols: number,
++    rows: number,
++    debug: boolean,
++    private _useConpty: boolean | undefined,
++    conptyInheritCursor: boolean = false
++  ) {
++    if (this._useConpty === undefined || this._useConpty === true) {
++      this._useConpty = this._getWindowsBuildNumber() >= 18309;
++    }
++    if (this._useConpty) {
++      if (!conptyNative) {
++        try {
++          conptyNative = require('../build/Release/conpty.node');
++        } catch (outerError) {
++          try {
++            conptyNative = require('../build/Debug/conpty.node');
++          } catch (innerError) {
++            console.error('innerError', innerError);
++            // Re-throw the exception from the Release require if the Debug require fails as well
++            throw outerError;
++          }
++        }
++      }
++    } else {
++      if (!winptyNative) {
++        try {
++          winptyNative = require('../build/Release/pty.node');
++        } catch (outerError) {
++          try {
++            winptyNative = require('../build/Debug/pty.node');
++          } catch (innerError) {
++            console.error('innerError', innerError);
++            // Re-throw the exception from the Release require if the Debug require fails as well
++            throw outerError;
++          }
++        }
++      }
++    }
++    this._ptyNative = this._useConpty ? conptyNative : winptyNative;
++
++    // Sanitize input variable.
++    cwd = path.resolve(cwd);
++
++    // Compose command line
++    const commandLine = argsToCommandLine(file, args);
++
++    // Open pty session.
++    let term: IConptyProcess | IWinptyProcess;
++    if (this._useConpty) {
++      term = (this._ptyNative as IConptyNative).startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor);
++    } else {
++      term = (this._ptyNative as IWinptyNative).startProcess(file, commandLine, env, cwd, cols, rows, debug);
++      this._pid = (term as IWinptyProcess).pid;
++      this._innerPid = (term as IWinptyProcess).innerPid;
++      this._innerPidHandle = (term as IWinptyProcess).innerPidHandle;
++    }
++
++    // Not available on windows.
++    this._fd = term.fd;
++
++    // Generated incremental number that has no real purpose besides  using it
++    // as a terminal id.
++    this._pty = term.pty;
++
++    // Create terminal pipe IPC channel and forward to a local unix socket.
++    this._outSocket = new Socket();
++    this._outSocket.setEncoding('utf8');
++    this._outSocket.connect(term.conout, () => {
++      // TODO: Emit event on agent instead of socket?
++
++      // Emit ready event.
++      this._outSocket.emit('ready_datapipe');
++    });
++
++    this._inSocket = new Socket();
++    this._inSocket.setEncoding('utf8');
++    this._inSocket.connect(term.conin);
++    // TODO: Wait for ready event?
++
++    if (this._useConpty) {
++      const connect = (this._ptyNative as IConptyNative).connect(this._pty, commandLine, cwd, env, c => this._$onProcessExit(c)
++);
++      this._innerPid = connect.pid;
++    }
++  }
++
++  public resize(cols: number, rows: number): void {
++    if (this._useConpty) {
++      if (this._exitCode !== undefined) {
++        throw new Error('Cannot resize a pty that has already exited');
++      }
++      this._ptyNative.resize(this._pty, cols, rows);
++      return;
++    }
++    this._ptyNative.resize(this._pid, cols, rows);
++  }
++
++  public kill(): void {
++    this._inSocket.readable = false;
++    this._inSocket.writable = false;
++    this._outSocket.readable = false;
++    this._outSocket.writable = false;
++    // Tell the agent to kill the pty, this releases handles to the process
++    if (this._useConpty) {
++      this._getConsoleProcessList().then(consoleProcessList => {
++        consoleProcessList.forEach((pid: number) => {
++          try {
++            process.kill(pid);
++          } catch (e) {
++            // Ignore if process cannot be found (kill ESRCH error)
++          }
++        });
++        (this._ptyNative as IConptyNative).kill(this._pty);
++      });
++    } else {
++      (this._ptyNative as IWinptyNative).kill(this._pid, this._innerPidHandle);
++      // Since pty.kill closes the handle it will kill most processes by itself
++      // and process IDs can be reused as soon as all handles to them are
++      // dropped, we want to immediately kill the entire console process list.
++      // If we do not force kill all processes here, node servers in particular
++      // seem to become detached and remain running (see
++      // Microsoft/vscode#26807).
++      const processList: number[] = (this._ptyNative as IWinptyNative).getProcessList(this._pid);
++      processList.forEach(pid => {
++        try {
++          process.kill(pid);
++        } catch (e) {
++          // Ignore if process cannot be found (kill ESRCH error)
++        }
++      });
++    }
++  }
++
++  private _getConsoleProcessList(): Promise<number[]> {
++    return new Promise<number[]>(resolve => {
++      const agent = fork(path.join(__dirname, 'conpty_console_list_agent'), [ this._innerPid.toString() ]);
++      agent.on('message', message => {
++        clearTimeout(timeout);
++        resolve(message.consoleProcessList);
++      });
++      const timeout = setTimeout(() => {
++        // Something went wrong, just send back the shell PID
++        agent.kill();
++        resolve([ this._innerPid ]);
++      }, 5000);
++    });
++  }
++
++  public get exitCode(): number {
++    if (this._useConpty) {
++      return this._exitCode;
++    }
++    return (this._ptyNative as IWinptyNative).getExitCode(this._innerPidHandle);
++  }
++
++  private _getWindowsBuildNumber(): number {
++    const osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
++    let buildNumber: number = 0;
++    if (osVersion && osVersion.length === 4) {
++      buildNumber = parseInt(osVersion[3]);
++    }
++    return buildNumber;
++  }
++
++  private _generatePipeName(): string {
++    return `conpty-${Math.random() * 10000000}`;
++  }
++
++  /**
++   * Triggered from the native side when a contpy process exits.
++   */
++  private _$onProcessExit(exitCode: number): void {
++    this._exitCode = exitCode;
++    this._flushDataAndCleanUp();
++    this._outSocket.on('data', () => this._flushDataAndCleanUp());
++  }
++
++  private _flushDataAndCleanUp(): void {
++    if (this._closeTimeout) {
++      clearTimeout(this._closeTimeout);
++    }
++    this._closeTimeout = setTimeout(() => this._cleanUpProcess(), FLUSH_DATA_INTERVAL);
++  }
++
++  private _cleanUpProcess(): void {
++    this._inSocket.readable = false;
++    this._inSocket.writable = false;
++    this._outSocket.readable = false;
++    this._outSocket.writable = false;
++    this._outSocket.destroy();
++  }
++}
++
++// Convert argc/argv into a Win32 command-line following the escaping convention
++// documented on MSDN (e.g. see CommandLineToArgvW documentation). Copied from
++// winpty project.
++export function argsToCommandLine(file: string, args: ArgvOrCommandLine): string {
++  if (isCommandLine(args)) {
++    if (args.length === 0) {
++      return file;
++    }
++    return `${argsToCommandLine(file, [])} ${args}`;
++  }
++  const argv = [file];
++  Array.prototype.push.apply(argv, args);
++  let result = '';
++  for (let argIndex = 0; argIndex < argv.length; argIndex++) {
++    if (argIndex > 0) {
++      result += ' ';
++    }
++    const arg = argv[argIndex];
++    // if it is empty or it contains whitespace and is not already quoted
++    const hasLopsidedEnclosingQuote = xOr((arg[0] !== '"'), (arg[arg.length - 1] !== '"'));
++    const hasNoEnclosingQuotes = ((arg[0] !== '"') && (arg[arg.length - 1] !== '"'));
++    const quote =
++      arg === '' ||
++      (arg.indexOf(' ') !== -1 ||
++      arg.indexOf('\t') !== -1) &&
++      ((arg.length > 1) &&
++      (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
++    if (quote) {
++      result += '\"';
++    }
++    let bsCount = 0;
++    for (let i = 0; i < arg.length; i++) {
++      const p = arg[i];
++      if (p === '\\') {
++        bsCount++;
++      } else if (p === '"') {
++        result += repeatText('\\', bsCount * 2 + 1);
++        result += '"';
++        bsCount = 0;
++      } else {
++        result += repeatText('\\', bsCount);
++        bsCount = 0;
++        result += p;
++      }
++    }
++    if (quote) {
++      result += repeatText('\\', bsCount * 2);
++      result += '\"';
++    } else {
++      result += repeatText('\\', bsCount);
++    }
++  }
++  return result;
++}
++
++function isCommandLine(args: ArgvOrCommandLine): args is string {
++  return typeof args === 'string';
++}
++
++function repeatText(text: string, count: number): string {
++  let result = '';
++  for (let i = 0; i < count; i++) {
++    result += text;
++  }
++  return result;
++}
++
++function xOr(arg1: boolean, arg2: boolean): boolean {
++  return ((arg1 && !arg2) || (!arg1 && arg2));
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..90441621d81dea49597f40cc73817bf2e7380a45
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,205 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import * as fs from 'fs';
++import * as assert from 'assert';
++import { WindowsTerminal } from './windowsTerminal';
++import * as path from 'path';
++import * as psList from 'ps-list';
++
++interface IProcessState {
++  // Whether the PID must exist or must not exist
++  [pid: number]: boolean;
++}
++
++interface IWindowsProcessTreeResult {
++  name: string;
++  pid: number;
++}
++
++function pollForProcessState(desiredState: IProcessState, intervalMs: number = 100, timeoutMs: number = 2000): Promise<void> {
++  return new Promise<void>(resolve => {
++    let tries = 0;
++    const interval = setInterval(() => {
++      psList({ all: true }).then(ps => {
++        let success = true;
++        const pids = Object.keys(desiredState).map(k => parseInt(k, 10));
++        pids.forEach(pid => {
++          if (desiredState[pid]) {
++            if (!ps.some(p => p.pid === pid)) {
++              success = false;
++            }
++          } else {
++            if (ps.some(p => p.pid === pid)) {
++              success = false;
++            }
++          }
++        });
++        if (success) {
++          clearInterval(interval);
++          resolve();
++          return;
++        }
++        tries++;
++        if (tries * intervalMs >= timeoutMs) {
++          clearInterval(interval);
++          const processListing = pids.map(k => `${k}: ${desiredState[k]}`).join('\n');
++          assert.fail(`Bad process state, expected:\n${processListing}`);
++          resolve();
++        }
++      });
++    }, intervalMs);
++  });
++}
++
++function pollForProcessTreeSize(pid: number, size: number, intervalMs: number = 100, timeoutMs: number = 2000): Promise<IWindowsProcessTreeResult[]> {
++  return new Promise<IWindowsProcessTreeResult[]>(resolve => {
++    let tries = 0;
++    const interval = setInterval(() => {
++      psList({ all: true }).then(ps => {
++        const openList: IWindowsProcessTreeResult[] = [];
++        openList.push(ps.filter(p => p.pid === pid).map(p => {
++          return { name: p.name, pid: p.pid };
++        })[0]);
++        const list: IWindowsProcessTreeResult[] = [];
++        while (openList.length) {
++          const current = openList.shift();
++          ps.filter(p => p.ppid === current.pid).map(p => {
++            return { name: p.name, pid: p.pid };
++          }).forEach(p => openList.push(p));
++          list.push(current);
++        }
++        const success = list.length === size;
++        if (success) {
++          clearInterval(interval);
++          resolve(list);
++          return;
++        }
++        tries++;
++        if (tries * intervalMs >= timeoutMs) {
++          clearInterval(interval);
++          assert.fail(`Bad process state, expected: ${size}, actual: ${list.length}`);
++          resolve();
++        }
++      });
++    }, intervalMs);
++  });
++}
++
++if (process.platform === 'win32') {
++  describe('WindowsTerminal', () => {
++    describe('kill', () => {
++      it('should not crash parent process', (done) => {
++        const term = new WindowsTerminal('cmd.exe', [], {});
++        term.kill();
++        // Add done call to deferred function queue to ensure the kill call has completed
++        (<any>term)._defer(done);
++      });
++      it('should kill the process tree', function (done: Mocha.Done): void {
++        this.timeout(5000);
++        const term = new WindowsTerminal('cmd.exe', [], {});
++        // Start sub-processes
++        term.write('powershell.exe\r');
++        term.write('notepad.exe\r');
++        term.write('node.exe\r');
++        pollForProcessTreeSize(term.pid, 4, 500, 5000).then(list => {
++          assert.equal(list[0].name, 'cmd.exe');
++          assert.equal(list[1].name, 'powershell.exe');
++          assert.equal(list[2].name, 'notepad.exe');
++          assert.equal(list[3].name, 'node.exe');
++          term.kill();
++          const desiredState: IProcessState = {};
++          desiredState[list[0].pid] = false;
++          desiredState[list[1].pid] = false;
++          desiredState[list[2].pid] = true;
++          desiredState[list[3].pid] = false;
++          pollForProcessState(desiredState).then(() => {
++            // Kill notepad before done
++            process.kill(list[2].pid);
++            done();
++          });
++        });
++      });
++    });
++
++    describe('resize', () => {
++      it('should throw a non-native exception when resizing an invalid value', () => {
++        const term = new WindowsTerminal('cmd.exe', [], {});
++        assert.throws(() => term.resize(-1, -1));
++        assert.throws(() => term.resize(0, 0));
++        assert.doesNotThrow(() => term.resize(1, 1));
++      });
++      it('should throw an non-native exception when resizing a killed terminal', (done) => {
++        const term = new WindowsTerminal('cmd.exe', [], {});
++        (<any>term)._defer(() => {
++          term.on('exit', () => {
++            assert.throws(() => term.resize(1, 1));
++            done();
++          });
++          term.destroy();
++        });
++      });
++    });
++
++    describe('Args as CommandLine', () => {
++      it('should not fail running a file containing a space in the path', (done) => {
++        const spaceFolder = path.resolve(__dirname, '..', 'fixtures', 'space folder');
++        if (!fs.existsSync(spaceFolder)) {
++          fs.mkdirSync(spaceFolder);
++        }
++
++        const cmdCopiedPath = path.resolve(spaceFolder, 'cmd.exe');
++        const data = fs.readFileSync(`${process.env.windir}\\System32\\cmd.exe`);
++        fs.writeFileSync(cmdCopiedPath, data);
++
++        if (!fs.existsSync(cmdCopiedPath)) {
++          // Skip test if git bash isn't installed
++          return;
++        }
++        const term = new WindowsTerminal(cmdCopiedPath, '/c echo "hello world"', {});
++        let result = '';
++        term.on('data', (data) => {
++          result += data;
++        });
++        term.on('exit', () => {
++          assert.ok(result.indexOf('hello world') >= 1);
++          done();
++        });
++      });
++    });
++
++    describe('env', () => {
++      it('should set environment variables of the shell', (done) => {
++        const term = new WindowsTerminal('cmd.exe', '/C echo %FOO%', { env: { FOO: 'BAR' }});
++        let result = '';
++        term.on('data', (data) => {
++          result += data;
++        });
++        term.on('exit', () => {
++          assert.ok(result.indexOf('BAR') >= 0);
++          done();
++        });
++      });
++    });
++
++    describe('On close', () => {
++      it('should return process zero exit codes', (done) => {
++        const term = new WindowsTerminal('cmd.exe', '/C exit');
++        term.on('exit', (code) => {
++          assert.equal(code, 0);
++          done();
++        });
++      });
++
++      it('should return process non-zero exit codes', (done) => {
++        const term = new WindowsTerminal('cmd.exe', '/C exit 2');
++        term.on('exit', (code) => {
++          assert.equal(code, 2);
++          done();
++        });
++      });
++    });
++  });
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..b0762883fb575423f76604cee88d24d60a50e222
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,187 @@@
++/**
++ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
++ * Copyright (c) 2016, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++import { Socket } from 'net';
++import { Terminal, DEFAULT_COLS, DEFAULT_ROWS } from './terminal';
++import { WindowsPtyAgent } from './windowsPtyAgent';
++import { IPtyOpenOptions, IWindowsPtyForkOptions } from './interfaces';
++import { ArgvOrCommandLine } from './types';
++import { assign } from './utils';
++
++const DEFAULT_FILE = 'cmd.exe';
++const DEFAULT_NAME = 'Windows Shell';
++
++export class WindowsTerminal extends Terminal {
++  private _isReady: boolean;
++  private _deferreds: any[];
++  private _agent: WindowsPtyAgent;
++
++  constructor(file?: string, args?: ArgvOrCommandLine, opt?: IWindowsPtyForkOptions) {
++    super(opt);
++
++    // Initialize arguments
++    args = args || [];
++    file = file || DEFAULT_FILE;
++    opt = opt || {};
++    opt.env = opt.env || process.env;
++
++    if (opt.encoding) {
++      console.warn('Setting encoding on Windows is not supported');
++    }
++
++    const env = assign({}, opt.env);
++    this._cols = opt.cols || DEFAULT_COLS;
++    this._rows = opt.rows || DEFAULT_ROWS;
++    const cwd = opt.cwd || process.cwd();
++    const name = opt.name || env.TERM || DEFAULT_NAME;
++    const parsedEnv = this._parseEnv(env);
++
++    // If the terminal is ready
++    this._isReady = false;
++
++    // Functions that need to run after `ready` event is emitted.
++    this._deferreds = [];
++
++    // Create new termal.
++    this._agent = new WindowsPtyAgent(file, args, parsedEnv, cwd, this._cols, this._rows, false, opt.useConpty, opt.conptyInheritCursor);
++    this._socket = this._agent.outSocket;
++
++    // Not available until `ready` event emitted.
++    this._pid = this._agent.innerPid;
++    this._fd = this._agent.fd;
++    this._pty = this._agent.pty;
++
++    // The forked windows terminal is not available until `ready` event is
++    // emitted.
++    this._socket.on('ready_datapipe', () => {
++
++      // These events needs to be forwarded.
++      ['connect', 'data', 'end', 'timeout', 'drain'].forEach(event => {
++        this._socket.on(event, () => {
++
++          // Wait until the first data event is fired then we can run deferreds.
++          if (!this._isReady && event === 'data') {
++
++            // Terminal is now ready and we can avoid having to defer method
++            // calls.
++            this._isReady = true;
++
++            // Execute all deferred methods
++            this._deferreds.forEach(fn => {
++              // NB! In order to ensure that `this` has all its references
++              // updated any variable that need to be available in `this` before
++              // the deferred is run has to be declared above this forEach
++              // statement.
++              fn.run();
++            });
++
++            // Reset
++            this._deferreds = [];
++
++          }
++        });
++      });
++
++      // Shutdown if `error` event is emitted.
++      this._socket.on('error', err => {
++        // Close terminal session.
++        this._close();
++
++        // EIO, happens when someone closes our child process: the only process
++        // in the terminal.
++        // node < 0.6.14: errno 5
++        // node >= 0.6.14: read EIO
++        if ((<any>err).code) {
++          if (~(<any>err).code.indexOf('errno 5') || ~(<any>err).code.indexOf('EIO')) return;
++        }
++
++        // Throw anything else.
++        if (this.listeners('error').length < 2) {
++          throw err;
++        }
++      });
++
++      // Cleanup after the socket is closed.
++      this._socket.on('close', () => {
++        this.emit('exit', this._agent.exitCode);
++        this._close();
++      });
++
++    });
++
++    this._file = file;
++    this._name = name;
++
++    this._readable = true;
++    this._writable = true;
++
++    this._forwardEvents();
++  }
++
++  protected _write(data: string): void {
++    this._defer(this._doWrite, data);
++  }
++
++  private _doWrite(data: string): void {
++    this._agent.inSocket.write(data);
++  }
++
++  /**
++   * openpty
++   */
++
++  public static open(options?: IPtyOpenOptions): void {
++    throw new Error('open() not supported on windows, use Fork() instead.');
++  }
++
++  /**
++   * TTY
++   */
++
++  public resize(cols: number, rows: number): void {
++    if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
++      throw new Error('resizing must be done using positive cols and rows');
++    }
++    this._defer(() => {
++      this._agent.resize(cols, rows);
++      this._cols = cols;
++      this._rows = rows;
++    });
++  }
++
++  public destroy(): void {
++    this._defer(() => {
++      this.kill();
++    });
++  }
++
++  public kill(signal?: string): void {
++    this._defer(() => {
++      if (signal) {
++        throw new Error('Signals not supported on windows.');
++      }
++      this._close();
++      this._agent.kill();
++    });
++  }
++
++  private _defer<A extends any>(deferredFn: (arg?: A) => void, arg?: A): void {
++    // If the terminal is ready, execute.
++    if (this._isReady) {
++      deferredFn.call(this, arg);
++      return;
++    }
++
++    // Queue until terminal is ready.
++    this._deferreds.push({
++      run: () => deferredFn.call(this, arg)
++    });
++  }
++
++  public get process(): string { return this._name; }
++  public get master(): Socket { throw new Error('master is not supported on Windows'); }
++  public get slave(): Socket { throw new Error('slave is not supported on Windows'); }
++}
index 0000000000000000000000000000000000000000,0000000000000000000000000000000000000000..5b1e0e4d1305449bb9699daea4afbc49d666369c
new file mode 100644 (file)
--- /dev/null
--- /dev/null
@@@ -1,0 -1,0 +1,202 @@@
++/**
++ * Copyright (c) 2017, Daniel Imms (MIT License).
++ * Copyright (c) 2018, Microsoft Corporation (MIT License).
++ */
++
++declare module 'node-pty' {
++  /**
++   * Forks a process as a pseudoterminal.
++   * @param file The file to launch.
++   * @param args The file's arguments as argv (string[]) or in a pre-escaped CommandLine format
++   * (string). Note that the CommandLine option is only available on Windows and is expected to be
++   * escaped properly.
++   * @param options The options of the terminal.
++   * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
++   * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
++   * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx
++   */
++  export function spawn(file: string, args: string[] | string, options: IPtyForkOptions | IWindowsPtyForkOptions): IPty;
++
++  export interface IBasePtyForkOptions {
++
++    /**
++     * Name of the terminal to be set in environment ($TERM variable).
++     */
++    name?: string;
++
++    /**
++     * Number of intial cols of the pty.
++     */
++    cols?: number;
++
++    /**
++     * Number of initial rows of the pty.
++     */
++    rows?: number;
++
++    /**
++     * Working directory to be set for the slave program.
++     */
++    cwd?: string;
++
++    /**
++     * Environment to be set for the slave program.
++     */
++    env?: { [key: string]: string };
++
++    /**
++     * String encoding of the underlying pty.
++     * If set, incoming data will be decoded to strings and outgoing strings to bytes applying this encoding.
++     * If unset, incoming data will be delivered as raw bytes (Buffer type).
++     * By default 'utf8' is assumed, to unset it explicitly set it to `null`.
++     */
++    encoding?: string | null;
++
++    /**
++     * (EXPERIMENTAL)
++     * Whether to enable flow control handling (false by default). If enabled a message of `flowControlPause`
++     * will pause the socket and thus blocking the slave program execution due to buffer back pressure.
++     * A message of `flowControlResume` will resume the socket into flow mode.
++     * For performance reasons only a single message as a whole will match (no message part matching).
++     * If flow control is enabled the `flowControlPause` and `flowControlResume` messages are not forwarded to
++     * the underlying pseudoterminal.
++     */
++    handleFlowControl?: boolean;
++
++    /**
++     * (EXPERIMENTAL)
++     * The string that should pause the pty when `handleFlowControl` is true. Default is XOFF ('\x13').
++     */
++    flowControlPause?: string;
++
++    /**
++     * (EXPERIMENTAL)
++     * The string that should resume the pty when `handleFlowControl` is true. Default is XON ('\x11').
++     */
++    flowControlResume?: string;
++  }
++
++  export interface IPtyForkOptions extends IBasePtyForkOptions {
++    /**
++     * Security warning: use this option with great caution, as opened file descriptors
++     * with higher privileges might leak to the slave program.
++     */
++    uid?: number;
++    gid?: number;
++  }
++
++  export interface IWindowsPtyForkOptions extends IBasePtyForkOptions {
++    /**
++     * Whether to use the ConPTY system on Windows. When this is not set, ConPTY will be used when
++     * the Windows build number is >= 18309 (instead of winpty). Note that ConPTY is available from
++     * build 17134 but is too unstable to enable by default.
++     *
++     * This setting does nothing on non-Windows.
++     */
++    useConpty?: boolean;
++
++    /**
++     * Whether to use PSEUDOCONSOLE_INHERIT_CURSOR in conpty.
++     * @see https://docs.microsoft.com/en-us/windows/console/createpseudoconsole
++     */
++    conptyInheritCursor?: boolean;
++  }
++
++  /**
++   * An interface representing a pseudoterminal, on Windows this is emulated via the winpty library.
++   */
++  export interface IPty {
++    /**
++     * The process ID of the outer process.
++     */
++    readonly pid: number;
++
++    /**
++     * The column size in characters.
++     */
++    readonly cols: number;
++
++    /**
++     * The row size in characters.
++     */
++    readonly rows: number;
++
++    /**
++     * The title of the active process.
++     */
++    readonly process: string;
++
++    /**
++     * (EXPERIMENTAL)
++     * Whether to handle flow control. Useful to disable/re-enable flow control during runtime.
++     * Use this for binary data that is likely to contain the `flowControlPause` string by accident.
++     */
++    handleFlowControl: boolean;
++
++    /**
++     * Adds an event listener for when a data event fires. This happens when data is returned from
++     * the pty.
++     * @returns an `IDisposable` to stop listening.
++     */
++    readonly onData: IEvent<string>;
++
++    /**
++     * Adds an event listener for when an exit event fires. This happens when the pty exits.
++     * @returns an `IDisposable` to stop listening.
++     */
++    readonly onExit: IEvent<{ exitCode: number, signal?: number }>;
++
++    /**
++     * Adds a listener to the data event, fired when data is returned from the pty.
++     * @param event The name of the event.
++     * @param listener The callback function.
++     * @deprecated Use IPty.onData
++     */
++    on(event: 'data', listener: (data: string) => void): void;
++
++    /**
++     * Adds a listener to the exit event, fired when the pty exits.
++     * @param event The name of the event.
++     * @param listener The callback function, exitCode is the exit code of the process and signal is
++     * the signal that triggered the exit. signal is not supported on Windows.
++     * @deprecated Use IPty.onExit
++     */
++    on(event: 'exit', listener: (exitCode: number, signal?: number) => void): void;
++
++    /**
++     * Resizes the dimensions of the pty.
++     * @param columns THe number of columns to use.
++     * @param rows The number of rows to use.
++     */
++    resize(columns: number, rows: number): void;
++
++    /**
++     * Writes data to the pty.
++     * @param data The data to write.
++     */
++    write(data: string): void;
++
++    /**
++     * Kills the pty.
++     * @param signal The signal to use, defaults to SIGHUP. This parameter is not supported on
++     * Windows.
++     * @throws Will throw when signal is used on Windows.
++     */
++    kill(signal?: string): void;
++  }
++
++  /**
++   * An object that can be disposed via a dispose function.
++   */
++  export interface IDisposable {
++    dispose(): void;
++  }
++
++  /**
++   * An event that can be listened to.
++   * @returns an `IDisposable` to stop listening.
++   */
++  export interface IEvent<T> {
++    (listener: (e: T) => any): IDisposable;
++  }
++}
diff --cc src/views/starter.ejs
index ead4f5f564506cbc4feb707ffb1dc031122d8bce,10988092443b910c57c4627afbe4edde0d2c7afd..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,156 -1,118 +1,0 @@@
--<!DOCTYPE html>
--<html>
--
--<head>
--  <title></title>
-   <!-- these are for the terminal -->
-   <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
-   <script src="node_modules/xterm/lib/xterm.js"></script>
 -  <!-- <link rel="stylesheet" type="text/css" href="/styles/main.css" /> -->
--  <%include ../../partials/head%>
-   <style media="screen">
-     body {
-       display: flex;
-       flex-flow: row wrap;
-     }
-     main {
-       width: 100%;
-       flex-grow: 2;
-     }
-     aside {
-       flex-grow: 1;
-     }
-     footer {
-       position: absolute;
-       top: 100%;
-     }
-     .buttons {
-       display: flex;
-       width: 100%;
-       margin: 0;
-       padding: 0;
-     }
-     button {
-       flex-grow: 1;
-       border: 0;
-       border-bottom: 2px black solid;
-       overflow: hidden;
-       width: 15em;
-       background-color: white;
-       transition: background-color 0.3s ease-in, color 0.3s ease-in;
-     }
-     button:hover {
-       background-color: darkgrey;
-       color: white
-     }
 -  <link rel="stylesheet" type="text/css" href="/styles/starter.css" />
--
-     textarea {
-       width: 25%;
-       font-size: 1.5em;
-       overflow: auto;
-       height: 15em;
-       background-color: rgba(255, 255, 255, 0.8);
-       padding: 0;
-       margin: 0;
-     }
-   </style>
--</head>
--<header>
--  <%include ../../partials/header%>
--</header>
--
--<body>
--
--  <main>
-     <div class="buttons">
-       <button type="button" name="button" onclick="startvsorc()">Iniciar VsoRc</button>
-       <button type="button" name="button" onclick="stopvsorc()">Detener VsoRc</button>
-       <button type="button" name="button" onclick="startcontroller()">Iniciar controlador</button>
-       <button type="button" name="button" onclick="stopcontroller()">Detener controlador</button>
 -    <div class="side">
 -
 -      <div class="panel">
 -        <textarea class="text" rows="20" cols="7" id="comandos" placeholder="Definicion de la red como: H1:S1"></textarea>
 -        <div class="buttons">
 -          <button type="button" name="button" onclick="startvsorc()">Iniciar VSoRC</button>
 -          <button type="button" name="button" onclick="stopvsorc()">Detener VSoRC</button>
 -          <button type="button" name="button" onclick="startcontroller()">Iniciar controlador</button>
 -          <button type="button" name="button" onclick="stopcontroller()">Detener controlador</button>
 -        </div>
 -      </div>
 -
 -      <div class="panel">
 -        <textarea class="text" disabled rows="20" cols="7" id="vsorcout" placeholder="Salida del sistema de consola"></textarea>
 -        <div class="buttons">
 -          <button type="button" name="button" onclick="startvsorc()">Ping all</button>
 -          <button type="button" name="button" onclick="stopvsorc()">Placement</button>
 -          <button type="button" name="button" onclick="startcontroller()">Iperf3</button>
 -        </div>
 -      </div>
 -
--    </div>
-     <textarea rows="20" cols="7" id="comandos"></textarea>
 -
 -    <div class="side">
 -
 -      <div class="panel">
 -        <textarea class="text" disabled rows="20" cols="7" id="vsorcout" placeholder="Salida del controlador"></textarea>
 -      </div>
 -
 -      <div class="panel">
 -
 -      </div>
 -
 -    </div>
 -
--    <script type="text/javascript">
--      let topo = document.getElementById('comandos') //Donde van escrito el DSL
--
--
--
--      function stopcontroller() {
--        let xhr = new XMLHttpRequest();
--        xhr.open('GET', '/stopcontroller', true);
--        xhr.onload = function() {
--          if (xhr.status == 200) { //can use this.status instead
--            //console.log(xhr.responseText);// para ver en la consola
--            console.log("controller stoped");
--          }
--        }
--        xhr.send();
--
--      }
--
--      function startcontroller() {
--        let xhr = new XMLHttpRequest();
--        xhr.open('GET', '/startcontroller', true);
--        //console.log(xhr); //para ver en la consola
--        xhr.onload = function() {
--          if (xhr.status == 200) { //can use this.status instead
--
--            console.log("controller started");
--          }
--        }
--        xhr.send();
--      }
--
--      function startvsorc() {
--        let xhr = new XMLHttpRequest();
--        topology = JSON.stringify(topo.value)
--        xhr.open('GET', '/startvsorc?topology=' + topology, true);
--        xhr.onload = function() {
--          if (xhr.status == 200) { //can use this.status instead
--            //console.log(xhr.responseText);// para ver en la consola
--            console.log("vsorc started");
--          }
--        }
--
--        xhr.send();
--
--      }
--
--      function stopvsorc() {
--        let xhr = new XMLHttpRequest();
--        xhr.open('GET', '/stopvsorc', true);
--        xhr.onload = function() {
--          if (xhr.status == 200) { //can use this.status instead
--            //console.log(xhr.responseText);// para ver en la consola
--            console.log("vsorc stopped");
--          }
--        }
--        xhr.send();
--      }
--    </script>
--  </main>
-   <aside class="">
-     <div class="terminal"></div>
-     <script>
-       var term = new Terminal();
-       term.open(document.getElementById('terminal'));
-       term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
-     </script>
-     <div class="statusproyect">
-     </div>
-   </aside>
--</body>
--<footer>
--  <%include ../../partials/footer%>
--</footer>
--
--
--</html>