-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathstream.cpp
571 lines (519 loc) · 22.3 KB
/
stream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "_stream.h"
#include "stream.h"
#include "handle.h"
#include "misc.h"
#include "readDataRaw.hpp"
#include "ApiRoutines.h"
#include "../types/inc/GlyphWidth.hpp"
#include "../interactivity/inc/ServiceLocator.hpp"
using Microsoft::Console::Interactivity::ServiceLocator;
static bool IsCommandLinePopupKey(const KEY_EVENT_RECORD& event)
{
if (WI_AreAllFlagsClear(event.dwControlKeyState, RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED | RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
{
switch (event.wVirtualKeyCode)
{
case VK_ESCAPE:
case VK_PRIOR:
case VK_NEXT:
case VK_END:
case VK_HOME:
case VK_LEFT:
case VK_UP:
case VK_RIGHT:
case VK_DOWN:
case VK_F2:
case VK_F4:
case VK_F7:
case VK_F9:
case VK_DELETE:
return true;
default:
break;
}
}
return false;
}
static bool IsCommandLineEditingKey(const KEY_EVENT_RECORD& event)
{
if (WI_AreAllFlagsClear(event.dwControlKeyState, RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED | RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
{
switch (event.wVirtualKeyCode)
{
case VK_ESCAPE:
case VK_PRIOR:
case VK_NEXT:
case VK_END:
case VK_HOME:
case VK_LEFT:
case VK_UP:
case VK_RIGHT:
case VK_DOWN:
case VK_INSERT:
case VK_DELETE:
case VK_F1:
case VK_F2:
case VK_F3:
case VK_F4:
case VK_F5:
case VK_F6:
case VK_F7:
case VK_F8:
case VK_F9:
return true;
default:
break;
}
}
if (WI_IsAnyFlagSet(event.dwControlKeyState, RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
{
switch (event.wVirtualKeyCode)
{
case VK_END:
case VK_HOME:
case VK_LEFT:
case VK_RIGHT:
return true;
default:
break;
}
}
if (WI_IsAnyFlagSet(event.dwControlKeyState, RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
{
switch (event.wVirtualKeyCode)
{
case VK_F7:
case VK_F10:
return true;
default:
break;
}
}
return false;
}
// Routine Description:
// - This routine is used in stream input. It gets input and filters it for unicode characters.
// Arguments:
// - pInputBuffer - The InputBuffer to read from
// - pwchOut - On a successful read, the char data read
// - Wait - true if a waited read should be performed
// - pCommandLineEditingKeys - if present, arrow keys will be
// returned. on output, if true, pwchOut contains virtual key code for
// arrow key.
// - pPopupKeys - if present, arrow keys will be
// returned. on output, if true, pwchOut contains virtual key code for
// arrow key.
// Return Value:
// - STATUS_SUCCESS on success or a relevant error code on failure.
[[nodiscard]] NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer,
_Out_ wchar_t* const pwchOut,
const bool Wait,
_Out_opt_ bool* const pCommandLineEditingKeys,
_Out_opt_ bool* const pPopupKeys,
_Out_opt_ DWORD* const pdwKeyState) noexcept
{
if (nullptr != pCommandLineEditingKeys)
{
*pCommandLineEditingKeys = false;
}
if (nullptr != pPopupKeys)
{
*pPopupKeys = false;
}
if (nullptr != pdwKeyState)
{
*pdwKeyState = 0;
}
for (;;)
{
InputEventQueue events;
const auto Status = pInputBuffer->Read(events, 1, false, Wait, true, true);
if (FAILED_NTSTATUS(Status))
{
return Status;
}
if (events.empty())
{
assert(!Wait);
return STATUS_UNSUCCESSFUL;
}
const auto& Event = events[0];
if (Event.EventType == KEY_EVENT)
{
auto commandLineEditKey = false;
if (pCommandLineEditingKeys)
{
commandLineEditKey = IsCommandLineEditingKey(Event.Event.KeyEvent);
}
else if (pPopupKeys)
{
commandLineEditKey = IsCommandLinePopupKey(Event.Event.KeyEvent);
}
if (pdwKeyState)
{
*pdwKeyState = Event.Event.KeyEvent.dwControlKeyState;
}
if (Event.Event.KeyEvent.uChar.UnicodeChar != 0 && !commandLineEditKey)
{
// chars that are generated using alt + numpad
if (!Event.Event.KeyEvent.bKeyDown && Event.Event.KeyEvent.wVirtualKeyCode == VK_MENU)
{
if (WI_IsFlagSet(Event.Event.KeyEvent.dwControlKeyState, ALTNUMPAD_BIT))
{
if (HIBYTE(Event.Event.KeyEvent.uChar.UnicodeChar))
{
const char chT[2] = {
static_cast<char>(HIBYTE(Event.Event.KeyEvent.uChar.UnicodeChar)),
static_cast<char>(LOBYTE(Event.Event.KeyEvent.uChar.UnicodeChar)),
};
*pwchOut = CharToWchar(chT, 2);
}
else
{
// Because USER doesn't know our codepage,
// it gives us the raw OEM char and we
// convert it to a Unicode character.
char chT = LOBYTE(Event.Event.KeyEvent.uChar.UnicodeChar);
*pwchOut = CharToWchar(&chT, 1);
}
}
else
{
*pwchOut = Event.Event.KeyEvent.uChar.UnicodeChar;
}
return STATUS_SUCCESS;
}
// Ignore Escape and Newline chars
if (Event.Event.KeyEvent.bKeyDown &&
(WI_IsFlagSet(pInputBuffer->InputMode, ENABLE_VIRTUAL_TERMINAL_INPUT) ||
(Event.Event.KeyEvent.wVirtualKeyCode != VK_ESCAPE &&
Event.Event.KeyEvent.uChar.UnicodeChar != UNICODE_LINEFEED)))
{
*pwchOut = Event.Event.KeyEvent.uChar.UnicodeChar;
return STATUS_SUCCESS;
}
}
if (Event.Event.KeyEvent.bKeyDown)
{
if (pCommandLineEditingKeys && commandLineEditKey)
{
*pCommandLineEditingKeys = true;
*pwchOut = static_cast<wchar_t>(Event.Event.KeyEvent.wVirtualKeyCode);
return STATUS_SUCCESS;
}
if (pPopupKeys && commandLineEditKey)
{
*pPopupKeys = true;
*pwchOut = static_cast<char>(Event.Event.KeyEvent.wVirtualKeyCode);
return STATUS_SUCCESS;
}
const auto zeroKey = OneCoreSafeVkKeyScanW(0);
if (LOBYTE(zeroKey) == Event.Event.KeyEvent.wVirtualKeyCode &&
WI_IsAnyFlagSet(Event.Event.KeyEvent.dwControlKeyState, ALT_PRESSED) == WI_IsFlagSet(zeroKey, 0x400) &&
WI_IsAnyFlagSet(Event.Event.KeyEvent.dwControlKeyState, CTRL_PRESSED) == WI_IsFlagSet(zeroKey, 0x200) &&
WI_IsAnyFlagSet(Event.Event.KeyEvent.dwControlKeyState, SHIFT_PRESSED) == WI_IsFlagSet(zeroKey, 0x100))
{
// This really is the character 0x0000
*pwchOut = Event.Event.KeyEvent.uChar.UnicodeChar;
return STATUS_SUCCESS;
}
}
}
}
}
// Routine Description:
// - if we have leftover input, copy as much fits into the user's
// buffer and return. we may have multi line input, if a macro
// has been defined that contains the $T character.
// Arguments:
// - inputBuffer - Pointer to input buffer to read from.
// - buffer - buffer to place read char data into
// - bytesRead - number of bytes read and filled into the buffer
// - readHandleState - input read handle data associated with this read operation
// - unicode - true if read should be unicode, false otherwise
// Return Value:
// - STATUS_NO_MEMORY in low memory situation
// - other relevant NTSTATUS codes
[[nodiscard]] static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer,
std::span<char> buffer,
size_t& bytesRead,
INPUT_READ_HANDLE_DATA& readHandleState,
const bool unicode)
try
{
bytesRead = 0;
const auto pending = readHandleState.GetPendingInput();
auto input = pending;
// This is basically the continuation of COOKED_READ_DATA::_handlePostCharInputLoop.
if (readHandleState.IsMultilineInput())
{
const auto firstLineEnd = input.find(UNICODE_LINEFEED) + 1;
input = input.substr(0, std::min(input.size(), firstLineEnd));
}
const auto inputSizeBefore = input.size();
std::span writer{ buffer };
inputBuffer.Consume(unicode, input, writer);
// Since we truncated `input` to only include the first line,
// we need to restore `input` here to the entirety of the remaining input.
if (readHandleState.IsMultilineInput())
{
const auto inputSizeAfter = input.size();
const auto amountConsumed = inputSizeBefore - inputSizeAfter;
input = pending.substr(std::min(pending.size(), amountConsumed));
}
if (input.empty())
{
readHandleState.CompletePending();
}
else
{
readHandleState.UpdatePending(input);
}
bytesRead = buffer.size() - writer.size();
return STATUS_SUCCESS;
}
NT_CATCH_RETURN()
// Routine Description:
// - read in characters until the buffer is full or return is read.
// since we may wait inside this loop, store all important variables
// in the read data structure. if we do wait, a read data structure
// will be allocated from the heap and its pointer will be stored
// in the wait block. the CookedReadData will be copied into the
// structure. the data is freed when the read is completed.
// Arguments:
// - inputBuffer - input buffer to read data from
// - processData - process handle of process making read request
// - buffer - buffer to place read char data
// - bytesRead - on output, the number of bytes read into pwchBuffer
// - controlKeyState - set by a cooked read
// - initialData - text of initial data found in the read message
// - ctrlWakeupMask - used by COOKED_READ_DATA
// - readHandleState - input read handle data associated with this read operation
// - exeName - name of the exe requesting the read
// - unicode - true if read should be unicode, false otherwise
// - waiter - If a wait is necessary this will contain the wait
// object on output
// Return Value:
// - STATUS_UNSUCCESSFUL if not able to access current screen buffer
// - STATUS_NO_MEMORY in low memory situation
// - other relevant HRESULT codes
[[nodiscard]] static HRESULT _ReadLineInput(InputBuffer& inputBuffer,
const HANDLE processData,
std::span<char> buffer,
size_t& bytesRead,
DWORD& controlKeyState,
const std::wstring_view initialData,
const DWORD ctrlWakeupMask,
INPUT_READ_HANDLE_DATA& readHandleState,
const std::wstring_view exeName,
const bool unicode,
std::unique_ptr<IWaitRoutine>& waiter) noexcept
{
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
RETURN_HR_IF(E_FAIL, !gci.HasActiveOutputBuffer());
auto& screenInfo = gci.GetActiveOutputBuffer();
try
{
auto cookedReadData = std::make_unique<COOKED_READ_DATA>(&inputBuffer, // pInputBuffer
&readHandleState, // pInputReadHandleData
screenInfo, // pScreenInfo
buffer.size_bytes(), // UserBufferSize
buffer.data(), // UserBuffer
ctrlWakeupMask, // CtrlWakeupMask
exeName, // exe name
initialData,
reinterpret_cast<ConsoleProcessHandle*>(processData)); //pClientProcess
gci.SetCookedReadData(cookedReadData.get());
bytesRead = buffer.size_bytes(); // This parameter on the way in is the size to read, on the way out, it will be updated to what is actually read.
if (!cookedReadData->Read(unicode, bytesRead, controlKeyState))
{
// memory will be cleaned up by wait queue
waiter.reset(cookedReadData.release());
}
else
{
gci.SetCookedReadData(nullptr);
}
}
CATCH_RETURN();
return S_OK;
}
// Routine Description:
// - Character (raw) mode. Read at least one character in. After one
// character has been read, get any more available characters and
// return. The first call to GetChar may block. If we do wait, a read
// data structure will be allocated from the heap and its pointer will
// be stored in the wait block. The RawReadData will be copied into
// the structure. The data is freed when the read is completed.
// Arguments:
// - inputBuffer - input buffer to read data from
// - buffer - on output, the amount of data read, in bytes
// - bytesRead - number of bytes read and placed into buffer
// - readHandleState - input read handle data associated with this read operation
// - unicode - true if read should be unicode, false otherwise
// - waiter - if a wait is necessary, on output this will contain
// the associated wait object
// Return Value:
// - CONSOLE_STATUS_WAIT if a wait is necessary. ppWaiter will be
// populated.
// - STATUS_SUCCESS on success
// - Other NTSTATUS codes as necessary
[[nodiscard]] NTSTATUS ReadCharacterInput(InputBuffer& inputBuffer,
std::span<char> buffer,
size_t& bytesRead,
INPUT_READ_HANDLE_DATA& readHandleState,
const bool unicode)
try
{
UNREFERENCED_PARAMETER(readHandleState);
bytesRead = 0;
const auto charSize = unicode ? sizeof(wchar_t) : sizeof(char);
std::span writer{ buffer };
if (writer.size() < charSize)
{
return STATUS_BUFFER_TOO_SMALL;
}
inputBuffer.ConsumeCached(unicode, writer);
auto noDataReadYet = writer.size() == buffer.size();
auto status = STATUS_SUCCESS;
while (writer.size() >= charSize)
{
wchar_t wch;
// We don't need to wait for input if `ConsumeCached` read something already, which is
// indicated by the writer having been advanced (= it's shorter than the original buffer).
status = GetChar(&inputBuffer, &wch, noDataReadYet, nullptr, nullptr, nullptr);
if (FAILED_NTSTATUS(status))
{
break;
}
std::wstring_view wchView{ &wch, 1 };
inputBuffer.Consume(unicode, wchView, writer);
noDataReadYet = false;
}
bytesRead = buffer.size() - writer.size();
// Once we read some data off the InputBuffer it can't be read again, so we
// need to make sure to return a success status to the client in that case.
return noDataReadYet ? status : STATUS_SUCCESS;
}
NT_CATCH_RETURN()
// Routine Description:
// - This routine reads in characters for stream input and does the
// required processing based on the input mode (line, char, echo).
// - This routine returns UNICODE characters.
// Arguments:
// - inputBuffer - Pointer to input buffer to read from.
// - processData - process handle of process making read request
// - buffer - buffer to place read char data into
// - bytesRead - the length of data placed in buffer. Measured in bytes.
// - controlKeyState - set by a cooked read
// - initialData - text of initial data found in the read message
// - ctrlWakeupMask - used by COOKED_READ_DATA
// - readHandleState - read handle data associated with this read
// - exeName- name of the exe requesting the read
// - unicode - true for a unicode read, false for ascii
// - waiter - If a wait is necessary this will contain the wait
// object on output
// Return Value:
// - STATUS_BUFFER_TOO_SMALL if pdwNumBytes is too small to store char
// data.
// - CONSOLE_STATUS_WAIT if a wait is necessary. ppWaiter will be
// populated.
// - STATUS_SUCCESS on success
// - Other NSTATUS codes as necessary
[[nodiscard]] NTSTATUS DoReadConsole(InputBuffer& inputBuffer,
const HANDLE processData,
std::span<char> buffer,
size_t& bytesRead,
ULONG& controlKeyState,
const std::wstring_view initialData,
const DWORD ctrlWakeupMask,
INPUT_READ_HANDLE_DATA& readHandleState,
const std::wstring_view exeName,
const bool unicode,
std::unique_ptr<IWaitRoutine>& waiter) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
waiter.reset();
bytesRead = 0;
if (buffer.size() < 1)
{
return STATUS_BUFFER_TOO_SMALL;
}
if (readHandleState.IsInputPending())
{
return _ReadPendingInput(inputBuffer,
buffer,
bytesRead,
readHandleState,
unicode);
}
else if (WI_IsFlagSet(inputBuffer.InputMode, ENABLE_LINE_INPUT))
{
return NTSTATUS_FROM_HRESULT(_ReadLineInput(inputBuffer,
processData,
buffer,
bytesRead,
controlKeyState,
initialData,
ctrlWakeupMask,
readHandleState,
exeName,
unicode,
waiter));
}
else
{
const auto status = ReadCharacterInput(inputBuffer,
buffer,
bytesRead,
readHandleState,
unicode);
if (status == CONSOLE_STATUS_WAIT)
{
waiter = std::make_unique<RAW_READ_DATA>(&inputBuffer, &readHandleState, gsl::narrow<ULONG>(buffer.size()), reinterpret_cast<wchar_t*>(buffer.data()));
}
return status;
}
}
CATCH_RETURN();
}
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleImpl(IConsoleInputObject& context,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::wstring_view initialData,
const std::wstring_view exeName,
INPUT_READ_HANDLE_DATA& readHandleState,
const bool IsUnicode,
const HANDLE clientHandle,
const DWORD controlWakeupMask,
DWORD& controlKeyState) noexcept
{
return HRESULT_FROM_NT(DoReadConsole(context,
clientHandle,
buffer,
written,
controlKeyState,
initialData,
controlWakeupMask,
readHandleState,
exeName,
IsUnicode,
waiter));
}
void UnblockWriteConsole(const DWORD dwReason)
{
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
gci.Flags &= ~dwReason;
if (WI_AreAllFlagsClear(gci.Flags, (CONSOLE_SUSPENDED | CONSOLE_SELECTING | CONSOLE_SCROLLBAR_TRACKING)))
{
// There is no longer any reason to suspend output, so unblock it.
gci.OutputQueue.NotifyWaiters(true);
}
}