-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathApiDispatchers.cpp
1916 lines (1530 loc) · 78.5 KB
/
ApiDispatchers.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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "ApiDispatchers.h"
#include "../host/directio.h"
#include "../host/getset.h"
#include "../host/stream.h"
#include "../host/srvinit.h"
#include "../host/cmdline.h"
// Assumes that it will find <m> in the calling environment.
#define TraceConsoleAPICallWithOrigin(ApiName, ...) \
TraceLoggingWrite( \
g_hConhostV2EventTraceProvider, \
"API_" ApiName, \
TraceLoggingPid(TraceGetProcessId(m), "OriginatingProcess"), \
TraceLoggingTid(TraceGetThreadId(m), "OriginatingThread"), \
__VA_ARGS__ __VA_OPT__(, ) \
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), \
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
static DWORD TraceGetProcessId(CONSOLE_API_MSG* const m)
{
const auto p = m->GetProcessHandle();
return p ? p->dwProcessId : 0;
}
static DWORD TraceGetThreadId(CONSOLE_API_MSG* const m)
{
const auto p = m->GetProcessHandle();
return p ? p->dwThreadId : 0;
}
template<typename T>
constexpr T saturate(auto val)
{
constexpr auto min = std::numeric_limits<T>::min();
constexpr auto max = std::numeric_limits<T>::max();
#pragma warning(suppress : 4267) // '...': conversion from '...' to 'T', possible loss of data
return val < min ? min : (val > max ? max : val);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCP(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL1.GetConsoleCP;
if (a->Output)
{
m->_pApiRoutines->GetConsoleOutputCodePageImpl(a->CodePage);
}
else
{
m->_pApiRoutines->GetConsoleInputCodePageImpl(a->CodePage);
}
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleMode(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL1.GetConsoleMode;
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
TraceConsoleAPICallWithOrigin(
"GetConsoleMode",
TraceLoggingBool(pObjectHandle->IsInputHandle(), "InputHandle"));
if (pObjectHandle->IsInputHandle())
{
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_READ, &pObj));
m->_pApiRoutines->GetConsoleInputModeImpl(*pObj, a->Mode);
}
else
{
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pObj));
m->_pApiRoutines->GetConsoleOutputModeImpl(*pObj, a->Mode);
}
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleMode(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL1.SetConsoleMode;
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
TraceConsoleAPICallWithOrigin(
"SetConsoleMode",
TraceLoggingBool(pObjectHandle->IsInputHandle(), "InputHandle"),
TraceLoggingHexUInt32(a->Mode, "Mode"));
if (pObjectHandle->IsInputHandle())
{
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleInputModeImpl(*pObj, a->Mode);
}
else
{
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleOutputModeImpl(*pObj, a->Mode);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetNumberOfInputEvents(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL1.GetNumberOfConsoleInputEvents;
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_READ, &pObj));
RETURN_IF_FAILED_EXPECTED(m->_pApiRoutines->GetNumberOfConsoleInputEventsImpl(*pObj, a->ReadyEvents));
TraceConsoleAPICallWithOrigin(
"GetNumberOfConsoleInputEvents",
TraceLoggingHexUInt32(a->ReadyEvents, "ReadyEvents"));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleInput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const pbReplyPending)
{
*pbReplyPending = FALSE;
const auto a = &m->u.consoleMsgL1.GetConsoleInput;
a->NumRecords = 0;
// If any flags are set that are not within our enum, it's invalid.
if (WI_IsAnyFlagSet(a->Flags, ~CONSOLE_READ_VALID))
{
return E_INVALIDARG;
}
// Make sure we have a valid input buffer.
const auto pHandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pHandleData);
InputBuffer* pInputBuffer;
RETURN_IF_FAILED(pHandleData->GetInputBuffer(GENERIC_READ, &pInputBuffer));
// Get output buffer.
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBufferSize));
const auto rgRecords = reinterpret_cast<INPUT_RECORD*>(pvBuffer);
const auto cRecords = cbBufferSize / sizeof(INPUT_RECORD);
TraceConsoleAPICallWithOrigin(
"GetConsoleInput",
TraceLoggingHexUInt16(a->Flags, "Flags"),
TraceLoggingBoolean(a->Unicode, "Unicode"),
TraceLoggingUIntPtr(cRecords, "Records"));
const auto fIsPeek = WI_IsFlagSet(a->Flags, CONSOLE_READ_NOREMOVE);
const auto fIsWaitAllowed = WI_IsFlagClear(a->Flags, CONSOLE_READ_NOWAIT);
const auto pInputReadHandleData = pHandleData->GetClientInput();
std::unique_ptr<IWaitRoutine> waiter;
InputEventQueue outEvents;
auto hr = m->_pApiRoutines->GetConsoleInputImpl(
*pInputBuffer,
outEvents,
cRecords,
*pInputReadHandleData,
a->Unicode,
fIsPeek,
waiter);
// We must return the number of records in the message payload (to alert the client)
// as well as in the message headers (below in SetReplyInformation) to alert the driver.
LOG_IF_FAILED(SizeTToULong(outEvents.size(), &a->NumRecords));
size_t cbWritten;
LOG_IF_FAILED(SizeTMult(outEvents.size(), sizeof(INPUT_RECORD), &cbWritten));
if (nullptr != waiter.get())
{
// In some circumstances, the read may have told us to wait because it didn't have data,
// but the client explicitly asked us to return immediate. In that case, we'll convert the
// wait request into a "0 bytes found, OK".
if (fIsWaitAllowed)
{
hr = ConsoleWaitQueue::s_CreateWait(m, waiter.release());
if (SUCCEEDED(hr))
{
*pbReplyPending = TRUE;
hr = CONSOLE_STATUS_WAIT;
}
}
else
{
// If wait isn't allowed and the routine generated a
// waiter, say there was nothing to be
// retrieved right now.
// The waiter will be auto-freed in the smart pointer.
cbWritten = 0;
hr = S_OK;
}
}
else
{
std::ranges::copy(outEvents, rgRecords);
}
if (SUCCEEDED(hr))
{
m->SetReplyInformation(cbWritten);
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const pbReplyPending)
{
*pbReplyPending = FALSE;
const auto a = &m->u.consoleMsgL1.ReadConsole;
a->NumBytes = 0; // we return 0 until proven otherwise.
// Make sure we have a valid input buffer.
const auto HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
InputBuffer* pInputBuffer;
RETURN_IF_FAILED(HandleData->GetInputBuffer(GENERIC_READ, &pInputBuffer));
// Get output parameter buffer.
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBufferSize));
// This might need to go on the other side of the fence (inside host) because the server doesn't know what we're going to do with initial num bytes.
// (This restriction exists because it's going to copy initial into the final buffer, but we don't know that.)
RETURN_HR_IF(E_INVALIDARG, a->InitialNumBytes > cbBufferSize);
// Retrieve input parameters.
// 1. Exe name making the request
const auto cchExeName = a->ExeNameLength;
ULONG cbExeName;
RETURN_IF_FAILED(ULongMult(cchExeName, sizeof(wchar_t), &cbExeName));
wistd::unique_ptr<wchar_t[]> pwsExeName;
if (cchExeName > 0)
{
pwsExeName = wil::make_unique_nothrow<wchar_t[]>(cchExeName);
RETURN_IF_NULL_ALLOC(pwsExeName);
RETURN_IF_FAILED(m->ReadMessageInput(0, pwsExeName.get(), cbExeName));
}
const std::wstring_view exeView(pwsExeName.get(), cchExeName);
// 2. Existing data in the buffer that was passed in.
std::unique_ptr<char[]> pbInitialData;
std::wstring_view initialData;
try
{
const auto cbInitialData = a->InitialNumBytes;
if (cbInitialData > 0)
{
// InitialNumBytes is only supported for ReadConsoleW (via CONSOLE_READCONSOLE_CONTROL::nInitialChars).
RETURN_HR_IF(E_INVALIDARG, !a->Unicode);
pbInitialData = std::make_unique<char[]>(cbInitialData);
// This parameter starts immediately after the exe name so skip by that many bytes.
RETURN_IF_FAILED(m->ReadMessageInput(cbExeName, pbInitialData.get(), cbInitialData));
initialData = { reinterpret_cast<const wchar_t*>(pbInitialData.get()), cbInitialData / sizeof(wchar_t) };
}
}
CATCH_RETURN();
TraceConsoleAPICallWithOrigin(
"ReadConsole",
TraceLoggingBoolean(a->Unicode, "Unicode"),
TraceLoggingBoolean(a->ProcessControlZ, "ProcessControlZ"),
TraceLoggingCountedWideString(exeView.data(), saturate<ULONG>(exeView.size()), "ExeName"),
TraceLoggingCountedWideString(initialData.data(), saturate<ULONG>(initialData.size()), "InitialChars"),
TraceLoggingHexUInt32(a->CtrlWakeupMask, "CtrlWakeupMask"));
// ReadConsole needs this to get details associated with an attached process (such as the command history list, telemetry metadata).
const auto hConsoleClient = (HANDLE)m->GetProcessHandle();
// ReadConsole needs this to store context information across "processed reads" e.g. reads on the same handle
// across multiple calls when we are simulating a command prompt input line for the client application.
const auto pInputReadHandleData = HandleData->GetClientInput();
std::unique_ptr<IWaitRoutine> waiter;
size_t cbWritten;
const std::span<char> outputBuffer(reinterpret_cast<char*>(pvBuffer), cbBufferSize);
auto hr = m->_pApiRoutines->ReadConsoleImpl(*pInputBuffer,
outputBuffer,
cbWritten, // We must set the reply length in bytes.
waiter,
initialData,
exeView,
*pInputReadHandleData,
a->Unicode,
hConsoleClient,
a->CtrlWakeupMask,
a->ControlKeyState);
LOG_IF_FAILED(SizeTToULong(cbWritten, &a->NumBytes));
if (nullptr != waiter.get())
{
// If we received a waiter, we need to queue the wait and not reply.
hr = ConsoleWaitQueue::s_CreateWait(m, waiter.release());
if (SUCCEEDED(hr))
{
*pbReplyPending = TRUE;
}
}
else
{
// - This routine is called when a ReadConsole or ReadFile request is about to be completed.
// - It sets the number of bytes written as the information to be written with the completion status and,
// if CTRL+Z processing is enabled and a CTRL+Z is detected, switches the number of bytes read to zero.
if (a->ProcessControlZ != FALSE &&
a->NumBytes > 0 &&
m->State.OutputBuffer != nullptr &&
*(PUCHAR)m->State.OutputBuffer == 0x1a)
{
a->NumBytes = 0;
}
m->SetReplyInformation(a->NumBytes);
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsole(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const pbReplyPending)
{
*pbReplyPending = FALSE;
const auto a = &m->u.consoleMsgL1.WriteConsole;
// Make sure we have a valid screen buffer.
auto HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
// Get input parameter buffer
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbBufferSize));
std::unique_ptr<IWaitRoutine> waiter;
size_t cbRead;
// We have to hold onto the HR from the call and return it.
// We can't return some other error after the actual API call.
// This is because the write console function is allowed to write part of the string and then return an error.
// It then must report back how far it got before it failed.
HRESULT hr;
if (a->Unicode)
{
const std::wstring_view buffer(reinterpret_cast<wchar_t*>(pvBuffer), cbBufferSize / sizeof(wchar_t));
size_t cchInputRead;
TraceConsoleAPICallWithOrigin(
"WriteConsoleW",
TraceLoggingUInt32(a->NumBytes, "NumBytes"),
TraceLoggingCountedWideString(buffer.data(), static_cast<ULONG>(buffer.size()), "Buffer"));
hr = m->_pApiRoutines->WriteConsoleWImpl(*pScreenInfo, buffer, cchInputRead, waiter);
// We must set the reply length in bytes. Convert back from characters.
LOG_IF_FAILED(SizeTMult(cchInputRead, sizeof(wchar_t), &cbRead));
}
else
{
const std::string_view buffer(reinterpret_cast<char*>(pvBuffer), cbBufferSize);
size_t cchInputRead;
TraceConsoleAPICallWithOrigin(
"WriteConsoleA",
TraceLoggingUInt32(a->NumBytes, "NumBytes"),
TraceLoggingCountedString(buffer.data(), static_cast<ULONG>(buffer.size()), "Buffer"));
hr = m->_pApiRoutines->WriteConsoleAImpl(*pScreenInfo, buffer, cchInputRead, waiter);
// Reply length is already in bytes (chars), don't need to convert.
cbRead = cchInputRead;
}
// We must return the byte length of the read data in the message.
LOG_IF_FAILED(SizeTToULong(cbRead, &a->NumBytes));
if (nullptr != waiter.get())
{
// If we received a waiter, we need to queue the wait and not reply.
hr = ConsoleWaitQueue::s_CreateWait(m, waiter.release());
if (SUCCEEDED(hr))
{
*pbReplyPending = TRUE;
}
}
else
{
// If no waiter, fill the response data and return.
m->SetReplyInformation(a->NumBytes);
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerFillConsoleOutput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.FillConsoleOutput;
// Capture length of initial fill.
const auto fill = a->Length;
// Set written length to 0 in case we early return.
a->Length = 0;
// Make sure we have a valid screen buffer.
auto HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
HRESULT hr;
size_t amountWritten;
switch (a->ElementType)
{
case CONSOLE_ATTRIBUTE:
{
TraceConsoleAPICallWithOrigin(
"FillConsoleOutputAttribute",
TraceLoggingConsoleCoord(a->WriteCoord, "WriteCoord"),
TraceLoggingUInt32(fill, "Length"),
TraceLoggingHexUInt16(a->Element, "Attribute"));
hr = m->_pApiRoutines->FillConsoleOutputAttributeImpl(*pScreenInfo,
a->Element,
fill,
til::wrap_coord(a->WriteCoord),
amountWritten,
m->GetProcessHandle()->GetShimPolicy().IsPowershellExe());
break;
}
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
{
TraceConsoleAPICallWithOrigin(
"FillConsoleOutputCharacterW",
TraceLoggingConsoleCoord(a->WriteCoord, "WriteCoord"),
TraceLoggingUInt32(fill, "Length"),
TraceLoggingWChar(a->Element, "Character"));
// GH#3126 if the client application is powershell.exe, then we might
// need to enable a compatibility shim.
hr = m->_pApiRoutines->FillConsoleOutputCharacterWImpl(*pScreenInfo,
a->Element,
fill,
til::wrap_coord(a->WriteCoord),
amountWritten,
m->GetProcessHandle()->GetShimPolicy().IsPowershellExe());
break;
}
case CONSOLE_ASCII:
{
TraceConsoleAPICallWithOrigin(
"FillConsoleOutputCharacterA",
TraceLoggingConsoleCoord(a->WriteCoord, "WriteCoord"),
TraceLoggingUInt32(fill, "Length"),
TraceLoggingChar(static_cast<char>(a->Element), "Character"));
hr = m->_pApiRoutines->FillConsoleOutputCharacterAImpl(*pScreenInfo,
static_cast<char>(a->Element),
fill,
til::wrap_coord(a->WriteCoord),
amountWritten);
break;
}
default:
return E_INVALIDARG;
}
LOG_IF_FAILED(SizeTToDWord(amountWritten, &a->Length));
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleActiveScreenBuffer(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
TraceConsoleAPICallWithOrigin("SetConsoleActiveScreenBuffer");
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
m->_pApiRoutines->SetConsoleActiveScreenBufferImpl(*pObj);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerFlushConsoleInputBuffer(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
TraceConsoleAPICallWithOrigin("ServerFlushConsoleInputBuffer");
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_WRITE, &pObj));
m->_pApiRoutines->FlushConsoleInputBuffer(*pObj);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCP(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleCP;
TraceConsoleAPICallWithOrigin(
"SetConsoleCP",
TraceLoggingBool(!a->Output, "InputHandle"),
TraceLoggingHexUInt32(a->CodePage, "CodePage"));
if (a->Output)
{
return m->_pApiRoutines->SetConsoleOutputCodePageImpl(a->CodePage);
}
else
{
return m->_pApiRoutines->SetConsoleInputCodePageImpl(a->CodePage);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.GetConsoleCursorInfo;
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
auto visible = false;
m->_pApiRoutines->GetConsoleCursorInfoImpl(*pObj, a->CursorSize, visible);
a->Visible = !!visible;
TraceConsoleAPICallWithOrigin(
"GetConsoleCursorInfo",
TraceLoggingUInt32(a->CursorSize, "CursorSize"),
TraceLoggingBoolean(a->Visible, "Visible"));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleCursorInfo;
TraceConsoleAPICallWithOrigin(
"SetConsoleCursorInfo",
TraceLoggingUInt32(a->CursorSize, "CursorSize"),
TraceLoggingBoolean(a->Visible, "Visible"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleCursorInfoImpl(*pObj, a->CursorSize, a->Visible);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.GetConsoleScreenBufferInfo;
CONSOLE_SCREEN_BUFFER_INFOEX ex = { 0 };
ex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pObj));
m->_pApiRoutines->GetConsoleScreenBufferInfoExImpl(*pObj, ex);
a->FullscreenSupported = !!ex.bFullscreenSupported;
const auto ColorTableSizeInBytes = RTL_NUMBER_OF_V2(ex.ColorTable) * sizeof(*ex.ColorTable);
CopyMemory(a->ColorTable, ex.ColorTable, ColorTableSizeInBytes);
a->CursorPosition = ex.dwCursorPosition;
a->MaximumWindowSize = ex.dwMaximumWindowSize;
a->Size = ex.dwSize;
a->ScrollPosition.X = ex.srWindow.Left;
a->ScrollPosition.Y = ex.srWindow.Top;
a->CurrentWindowSize.X = ex.srWindow.Right - ex.srWindow.Left;
a->CurrentWindowSize.Y = ex.srWindow.Bottom - ex.srWindow.Top;
a->Attributes = ex.wAttributes;
a->PopupAttributes = ex.wPopupAttributes;
TraceConsoleAPICallWithOrigin(
"GetConsoleScreenBufferInfo",
TraceLoggingConsoleCoord(a->Size, "Size"),
TraceLoggingConsoleCoord(a->CursorPosition, "CursorPosition"),
TraceLoggingConsoleCoord(a->ScrollPosition, "ScrollPosition"),
TraceLoggingHexUInt16(a->Attributes, "Attributes"),
TraceLoggingConsoleCoord(a->CurrentWindowSize, "CurrentWindowSize"),
TraceLoggingConsoleCoord(a->MaximumWindowSize, "MaximumWindowSize"),
TraceLoggingHexUInt16(a->PopupAttributes, "PopupAttributes"),
TraceLoggingBoolean(a->FullscreenSupported, "FullscreenSupported"),
TraceLoggingHexULongFixedArray(&a->ColorTable[0], 16, "ColorTable"));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleScreenBufferInfo;
TraceConsoleAPICallWithOrigin(
"SetConsoleScreenBufferInfo",
TraceLoggingConsoleCoord(a->Size, "Size"),
TraceLoggingConsoleCoord(a->CursorPosition, "CursorPosition"),
TraceLoggingConsoleCoord(a->ScrollPosition, "ScrollPosition"),
TraceLoggingHexUInt16(a->Attributes, "Attributes"),
TraceLoggingConsoleCoord(a->CurrentWindowSize, "CurrentWindowSize"),
TraceLoggingConsoleCoord(a->MaximumWindowSize, "MaximumWindowSize"),
TraceLoggingHexUInt16(a->PopupAttributes, "PopupAttributes"),
TraceLoggingBoolean(a->FullscreenSupported, "FullscreenSupported"),
TraceLoggingHexULongFixedArray(&a->ColorTable[0], 16, "ColorTable"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
CONSOLE_SCREEN_BUFFER_INFOEX ex = { 0 };
ex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
ex.bFullscreenSupported = a->FullscreenSupported;
const auto ColorTableSizeInBytes = RTL_NUMBER_OF_V2(ex.ColorTable) * sizeof(*ex.ColorTable);
CopyMemory(ex.ColorTable, a->ColorTable, ColorTableSizeInBytes);
ex.dwCursorPosition = a->CursorPosition;
ex.dwMaximumWindowSize = a->MaximumWindowSize;
ex.dwSize = a->Size;
ex.srWindow = { 0 };
ex.srWindow.Left = a->ScrollPosition.X;
ex.srWindow.Top = a->ScrollPosition.Y;
ex.srWindow.Right = ex.srWindow.Left + a->CurrentWindowSize.X;
ex.srWindow.Bottom = ex.srWindow.Top + a->CurrentWindowSize.Y;
ex.wAttributes = a->Attributes;
ex.wPopupAttributes = a->PopupAttributes;
return m->_pApiRoutines->SetConsoleScreenBufferInfoExImpl(*pObj, ex);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleScreenBufferSize(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleScreenBufferSize;
TraceConsoleAPICallWithOrigin(
"SetConsoleScreenBufferSize",
TraceLoggingConsoleCoord(a->Size, "BufferSize"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleScreenBufferSizeImpl(*pObj, til::wrap_coord_size(a->Size));
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCursorPosition(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleCursorPosition;
TraceConsoleAPICallWithOrigin(
"SetConsoleCursorPosition",
TraceLoggingConsoleCoord(a->CursorPosition, "CursorPosition"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleCursorPositionImpl(*pObj, til::wrap_coord(a->CursorPosition));
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetLargestConsoleWindowSize(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.GetLargestConsoleWindowSize;
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
auto size = til::wrap_coord_size(a->Size);
m->_pApiRoutines->GetLargestConsoleWindowSizeImpl(*pObj, size);
RETURN_IF_FAILED_EXPECTED(til::unwrap_coord_size_hr(size, a->Size));
TraceConsoleAPICallWithOrigin(
"GetLargestConsoleWindowSize",
TraceLoggingConsoleCoord(a->Size, "Size"));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerScrollConsoleScreenBuffer(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.ScrollConsoleScreenBuffer;
TraceConsoleAPICallWithOrigin(
"ScrollConsoleScreenBuffer",
TraceLoggingConsoleSmallRect(a->ScrollRectangle, "ScrollRectangle"),
TraceLoggingConsoleSmallRect(a->ClipRectangle, "ClipRectangle"),
TraceLoggingBoolean(a->Clip, "Clip"),
TraceLoggingBoolean(a->Unicode, "Unicode"),
TraceLoggingConsoleCoord(a->DestinationOrigin, "DestinationOrigin"),
TraceLoggingConsoleCharInfo(a->Fill, "Fill"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
if (a->Unicode)
{
// GH#3126 if the client application is cmd.exe, then we might need to
// enable a compatibility shim.
return m->_pApiRoutines->ScrollConsoleScreenBufferWImpl(*pObj,
til::wrap_small_rect(a->ScrollRectangle),
til::wrap_coord(a->DestinationOrigin),
a->Clip ? std::optional{ til::wrap_small_rect(a->ClipRectangle) } : std::nullopt,
a->Fill.Char.UnicodeChar,
a->Fill.Attributes,
m->GetProcessHandle()->GetShimPolicy().IsCmdExe());
}
else
{
return m->_pApiRoutines->ScrollConsoleScreenBufferAImpl(*pObj,
til::wrap_small_rect(a->ScrollRectangle),
til::wrap_coord(a->DestinationOrigin),
a->Clip ? std::optional{ til::wrap_small_rect(a->ClipRectangle) } : std::nullopt,
a->Fill.Char.AsciiChar,
a->Fill.Attributes);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleTextAttribute(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleTextAttribute;
TraceConsoleAPICallWithOrigin(
"SetConsoleTextAttribute",
TraceLoggingHexUInt16(a->Attributes, "Attributes"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
RETURN_HR(m->_pApiRoutines->SetConsoleTextAttributeImpl(*pObj, a->Attributes));
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleWindowInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.SetConsoleWindowInfo;
TraceConsoleAPICallWithOrigin(
"SetConsoleWindowInfo",
TraceLoggingBool(a->Absolute, "IsWindowRectAbsolute"),
TraceLoggingConsoleSmallRect(a->Window, "Window"));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleWindowInfoImpl(*pObj, a->Absolute, til::wrap_small_rect(a->Window));
}
[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsoleOutputString(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanReadOutputBuffer());
const auto a = &m->u.consoleMsgL2.ReadConsoleOutputString;
a->NumRecords = 0; // Set to 0 records returned in case we have failures.
PVOID pvBuffer;
ULONG cbBuffer;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBuffer));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pScreenInfo));
size_t written;
switch (a->StringType)
{
case CONSOLE_ATTRIBUTE:
{
const std::span<WORD> buffer(reinterpret_cast<WORD*>(pvBuffer), cbBuffer / sizeof(WORD));
TraceConsoleAPICallWithOrigin(
"ReadConsoleOutputAttribute",
TraceLoggingConsoleCoord(a->ReadCoord, "ReadCoord"),
TraceLoggingUIntPtr(buffer.size(), "Records"));
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputAttributeImpl(*pScreenInfo, til::wrap_coord(a->ReadCoord), buffer, written));
break;
}
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
{
const std::span<wchar_t> buffer(reinterpret_cast<wchar_t*>(pvBuffer), cbBuffer / sizeof(wchar_t));
TraceConsoleAPICallWithOrigin(
"ReadConsoleOutputCharacterW",
TraceLoggingConsoleCoord(a->ReadCoord, "ReadCoord"),
TraceLoggingUIntPtr(buffer.size(), "Records"));
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputCharacterWImpl(*pScreenInfo, til::wrap_coord(a->ReadCoord), buffer, written));
break;
}
case CONSOLE_ASCII:
{
const std::span<char> buffer(reinterpret_cast<char*>(pvBuffer), cbBuffer);
TraceConsoleAPICallWithOrigin(
"ReadConsoleOutputCharacterA",
TraceLoggingConsoleCoord(a->ReadCoord, "ReadCoord"),
TraceLoggingUIntPtr(buffer.size(), "Records"));
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputCharacterAImpl(*pScreenInfo, til::wrap_coord(a->ReadCoord), buffer, written));
break;
}
default:
return E_INVALIDARG;
}
// Report count of records now in the buffer (varies based on type)
RETURN_IF_FAILED(SizeTToULong(written, &a->NumRecords));
m->SetReplyInformation(cbBuffer); // Set the reply buffer size to what we were originally told the buffer size was (on the way in)
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleInput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.WriteConsoleInput;
a->NumRecords = 0;
RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanWriteInputBuffer());
PVOID pvBuffer;
ULONG cbSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbSize));
const auto pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
InputBuffer* pInputBuffer;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_WRITE, &pInputBuffer));
size_t written;
std::span<const INPUT_RECORD> buffer(reinterpret_cast<INPUT_RECORD*>(pvBuffer), cbSize / sizeof(INPUT_RECORD));
TraceConsoleAPICallWithOrigin(
"WriteConsoleInput",
TraceLoggingBoolean(a->Unicode, "Unicode"),
TraceLoggingBoolean(a->Append, "Append"),
TraceLoggingUIntPtr(buffer.size(), "Records"));
if (!a->Unicode)
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleInputAImpl(*pInputBuffer, buffer, written, !!a->Append));
}
else
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleInputWImpl(*pInputBuffer, buffer, written, !!a->Append));
}
RETURN_IF_FAILED(SizeTToULong(written, &a->NumRecords));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleOutput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.WriteConsoleOutput;
// Backup originalRegion and set the written area to a 0 size rectangle in case of failures.
const auto originalRegion = Microsoft::Console::Types::Viewport::FromInclusive(til::wrap_small_rect(a->CharRegion));
auto writtenRegion = Microsoft::Console::Types::Viewport::FromDimensions(originalRegion.Origin(), { 0, 0 });
RETURN_IF_FAILED(til::unwrap_small_rect_hr(writtenRegion.ToInclusive(), a->CharRegion));
// Get input parameter buffer
PVOID pvBuffer;
ULONG cbSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbSize));
// Make sure we have a valid screen buffer.
auto HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
// Validate parameters
size_t regionArea;
RETURN_IF_FAILED(SizeTMult(originalRegion.Dimensions().width, originalRegion.Dimensions().height, ®ionArea));
size_t regionBytes;
RETURN_IF_FAILED(SizeTMult(regionArea, sizeof(CHAR_INFO), ®ionBytes));
RETURN_HR_IF(E_INVALIDARG, cbSize < regionBytes); // If given fewer bytes on input than we need to do this write, it's invalid.
const std::span<CHAR_INFO> buffer(reinterpret_cast<CHAR_INFO*>(pvBuffer), cbSize / sizeof(CHAR_INFO));
TraceConsoleAPICallWithOrigin(
"WriteConsoleOutput",
TraceLoggingBoolean(a->Unicode, "Unicode"),
TraceLoggingConsoleSmallRect(a->CharRegion, "CharRegion"),
TraceLoggingUIntPtr(buffer.size(), "Records"));
if (!a->Unicode)
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleOutputAImpl(*pScreenInfo, buffer, originalRegion, writtenRegion));
}
else
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleOutputWImpl(*pScreenInfo, buffer, originalRegion, writtenRegion));
}
// Update the written region if we were successful
return til::unwrap_small_rect_hr(writtenRegion.ToInclusive(), a->CharRegion);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleOutputString(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
const auto a = &m->u.consoleMsgL2.WriteConsoleOutputString;
// Set written records to 0 in case we early return.
a->NumRecords = 0;
// Make sure we have a valid screen buffer.
auto HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
// Get input parameter buffer
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbBufferSize));