- Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathConsoleArguments.cpp
663 lines (611 loc) · 20.8 KB
/
ConsoleArguments.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include"precomp.h"
#include"ConsoleArguments.hpp"
#include"../types/inc/utils.hpp"
#include<shellapi.h>
usingnamespaceMicrosoft::Console::Utils;
const std::wstring_view ConsoleArguments::HEADLESS_ARG = L"--headless";
const std::wstring_view ConsoleArguments::SERVER_HANDLE_ARG = L"--server";
const std::wstring_view ConsoleArguments::SIGNAL_HANDLE_ARG = L"--signal";
const std::wstring_view ConsoleArguments::HANDLE_PREFIX = L"0x";
const std::wstring_view ConsoleArguments::CLIENT_COMMANDLINE_ARG = L"--";
const std::wstring_view ConsoleArguments::FORCE_V1_ARG = L"-ForceV1";
const std::wstring_view ConsoleArguments::FORCE_NO_HANDOFF_ARG = L"-ForceNoHandoff";
const std::wstring_view ConsoleArguments::FILEPATH_LEADER_PREFIX = L"\\??\\";
const std::wstring_view ConsoleArguments::WIDTH_ARG = L"--width";
const std::wstring_view ConsoleArguments::HEIGHT_ARG = L"--height";
const std::wstring_view ConsoleArguments::INHERIT_CURSOR_ARG = L"--inheritcursor";
const std::wstring_view ConsoleArguments::FEATURE_ARG = L"--feature";
const std::wstring_view ConsoleArguments::FEATURE_PTY_ARG = L"pty";
const std::wstring_view ConsoleArguments::COM_SERVER_ARG = L"-Embedding";
staticconstexpr std::wstring_view GLYPH_WIDTH{ L"--textMeasurement" };
// NOTE: Thinking about adding more commandline args that control conpty, for
// the Terminal? Make sure you add them to the commandline in
// ConsoleEstablishHandoff. We use that to initialize the ConsoleArguments for a
// defterm handoff s.t. they behave like a conpty connection that was started by
// the terminal. If you forget them there, the conpty won't obey them, only for
// defterm.
std::wstring EscapeArgument(std::wstring_view ac)
{
if (ac.empty())
{
returnL"\"\"";
}
auto hasSpace = false;
auto n = ac.size();
for (auto c : ac)
{
switch (c)
{
case L'"':
case L'\\':
n++;
break;
case'':
case'\t':
hasSpace = true;
break;
default:
break;
}
}
if (hasSpace)
{
n += 2;
}
if (n == ac.size())
{
return std::wstring{ ac };
}
std::wstring buf;
if (hasSpace)
{
buf.push_back(L'"');
}
size_t slashes = 0;
for (auto c : ac)
{
switch (c)
{
case L'\\':
slashes++;
buf.push_back(L'\\');
break;
case L'"':
{
for (; slashes > 0; slashes--)
{
buf.push_back(L'\\');
}
buf.push_back(L'\\');
buf.push_back(c);
}
break;
default:
slashes = 0;
buf.push_back(c);
break;
}
}
if (hasSpace)
{
for (; slashes > 0; slashes--)
{
buf.push_back(L'\\');
}
buf.push_back(L'"');
}
return buf;
}
ConsoleArguments::ConsoleArguments(const std::wstring& commandline,
const HANDLE hStdIn,
const HANDLE hStdOut) :
_commandline(commandline),
_vtInHandle(hStdIn),
_vtOutHandle(hStdOut)
{
_clientCommandline = L"";
_headless = false;
_runAsComServer = false;
_createServerHandle = true;
_serverHandle = 0;
_signalHandle = 0;
_forceV1 = false;
_forceNoHandoff = false;
_width = 0;
_height = 0;
_inheritCursor = false;
}
ConsoleArguments::ConsoleArguments() :
ConsoleArguments(L"", nullptr, nullptr)
{
}
ConsoleArguments& ConsoleArguments::operator=(const ConsoleArguments& other)
{
if (this != &other)
{
_commandline = other._commandline;
_clientCommandline = other._clientCommandline;
_vtInHandle = other._vtInHandle;
_vtOutHandle = other._vtOutHandle;
_headless = other._headless;
_createServerHandle = other._createServerHandle;
_serverHandle = other._serverHandle;
_signalHandle = other._signalHandle;
_forceV1 = other._forceV1;
_width = other._width;
_height = other._height;
_inheritCursor = other._inheritCursor;
_runAsComServer = other._runAsComServer;
_forceNoHandoff = other._forceNoHandoff;
}
return *this;
}
// Routine Description:
// - Consumes the argument at the given index off of the vector.
// Arguments:
// - args - The vector full of args
// - index - The item to consume/remove from the vector.
// Return Value:
// - <none>
voidConsoleArguments::s_ConsumeArg(_Inout_ std::vector<std::wstring>& args, _In_ size_t& index)
{
args.erase(args.begin() + index);
}
// Routine Description:
// Given the commandline of tokens `args`, tries to find the argument at
// index+1, and places its value into pSetting.
// If there aren't enough args, then returns E_INVALIDARG.
// If we found a value, then we take the elements at both index and index+1 out
// of args. We'll also decrement index, so that a caller who is using index
// as a loop index will autoincrement it to have it point at the correct
// next index.
//
// EX: for args=[--foo, bar, --baz]
// index=0 would place "bar" in pSetting,
// args is now [--baz], index is now -1, caller increments to 0
// index=2 would return E_INVALIDARG,
// args is still [--foo, bar, --baz], index is still 2, caller increments to 3.
// Arguments:
// args: A collection of wstrings representing command-line arguments
// index: the index of the argument of which to get the value for. The value
// should be at (index+1). index will be decremented by one on success.
// pSetting: receives the string at index+1
// Return Value:
// S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating
// failure.
[[nodiscard]] HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args,
_Inout_ size_t& index,
_Out_opt_ std::wstring* const pSetting)
{
auto hasNext = (index + 1) < args.size();
if (hasNext)
{
s_ConsumeArg(args, index);
if (pSetting != nullptr)
{
*pSetting = args[index];
}
s_ConsumeArg(args, index);
}
return (hasNext) ? S_OK : E_INVALIDARG;
}
// Routine Description:
// Similar to s_GetArgumentValue.
// Attempts to get the next arg as a "feature" arg - this can be used for
// feature detection.
// If the next arg is not recognized, then we don't support that feature.
// Currently, the only supported feature arg is `pty`, to identify pty support.
// Arguments:
// args: A collection of wstrings representing command-line arguments
// index: the index of the argument of which to get the value for. The value
// should be at (index+1). index will be decremented by one on success.
// pSetting: receives the string at index+1
// Return Value:
// S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating
// failure.
[[nodiscard]] HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector<std::wstring>& args, _Inout_ size_t& index)
{
auto hr = E_INVALIDARG;
auto hasNext = (index + 1) < args.size();
if (hasNext)
{
s_ConsumeArg(args, index);
auto value = args[index];
if (value == FEATURE_PTY_ARG)
{
hr = S_OK;
}
s_ConsumeArg(args, index);
}
return (hasNext) ? hr : E_INVALIDARG;
}
// Method Description:
// Routine Description:
// Given the commandline of tokens `args`, tries to find the argument at
// index+1, and places its value into pSetting. See above for examples.
// This implementation attempts to parse a short from the argument.
// Arguments:
// args: A collection of wstrings representing command-line arguments
// index: the index of the argument of which to get the value for. The value
// should be at (index+1). index will be decremented by one on success.
// pSetting: receives the short at index+1
// Return Value:
// S_OK if we parsed the short successfully, otherwise E_INVALIDARG indicating
// failure. This could be the case for non-numeric arguments, or for >SHORT_MAX args.
[[nodiscard]] HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args,
_Inout_ size_t& index,
_Out_opt_ short* const pSetting)
{
auto succeeded = (index + 1) < args.size();
if (succeeded)
{
s_ConsumeArg(args, index);
if (pSetting != nullptr)
{
try
{
size_t pos = 0;
auto value = std::stoi(args[index], &pos);
// If the entire string was a number, pos will be equal to the
// length of the string. Otherwise, a string like 8foo will
// be parsed as "8"
if (value > SHORT_MAX || pos != args[index].length())
{
succeeded = false;
}
else
{
*pSetting = static_cast<short>(value);
succeeded = true;
}
}
catch (...)
{
succeeded = false;
}
}
s_ConsumeArg(args, index);
}
return (succeeded) ? S_OK : E_INVALIDARG;
}
// Routine Description:
// - Parsing helper that will turn a string into a handle value if possible.
// Arguments:
// - handleAsText - The string representation of the handle that was passed in on the command line
// - handleAsVal - The location to store the value if we can appropriately convert it.
// Return Value:
// - S_OK if we could successfully parse the given text and store it in the handle value location.
// - E_INVALIDARG if we couldn't parse the text as a valid hex-encoded handle number OR
// if the handle value was already filled.
[[nodiscard]] HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _Inout_ DWORD& handleAsVal)
{
auto hr = S_OK;
// The handle should have a valid prefix.
if (handleAsText.substr(0, HANDLE_PREFIX.length()) != HANDLE_PREFIX)
{
hr = E_INVALIDARG;
}
elseif (0 == handleAsVal)
{
handleAsVal = wcstoul(handleAsText.c_str(), nullptr/*endptr*/, 16/*base*/);
// If the handle didn't parse into a reasonable handle ID, invalid.
if (handleAsVal == 0)
{
hr = E_INVALIDARG;
}
}
else
{
// If we're trying to set the handle a second time, invalid.
hr = E_INVALIDARG;
}
return hr;
}
// Routine Description:
// Given the commandline of tokens `args`, creates a wstring containing all of
// the remaining args after index joined with spaces. If skipFirst==true,
// then we omit the argument at index from this finished string. skipFirst
// should only be true if the first arg is
// ConsoleArguments::CLIENT_COMMANDLINE_ARG. Removes all the args starting
// at index from the collection.
// The finished commandline is placed in _clientCommandline
// Arguments:
// args: A collection of wstrings representing command-line arguments
// index: the index of the argument of which to start the commandline from.
// skipFirst: if true, omit the arg at index (which should be "--")
// Return Value:
// S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating
// failure.
[[nodiscard]] HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector<std::wstring>& args, constsize_t index, constbool skipFirst)
{
auto start = args.begin() + index;
// Erase the first token.
// Used to get rid of the explicit commandline token "--"
if (skipFirst)
{
// Make sure that the arg we're deleting is "--"
FAIL_FAST_IF(!(CLIENT_COMMANDLINE_ARG == start->c_str()));
args.erase(start);
}
_clientCommandline = L"";
size_t j = 0;
for (j = index; j < args.size(); j++)
{
_clientCommandline += EscapeArgument(args[j]); // escape commandline
if (j + 1 < args.size())
{
_clientCommandline += L"";
}
}
args.erase(args.begin() + index, args.begin() + j);
return S_OK;
}
// Routine Description:
// Attempts to parse the commandline that this ConsoleArguments was initialized
// with. Fills all of our members with values that were specified on the
// commandline.
// Arguments:
// <none>
// Return Value:
// S_OK if we parsed our _commandline successfully, otherwise E_INVALIDARG
// indicating failure.
[[nodiscard]] HRESULT ConsoleArguments::ParseCommandline()
{
// If the commandline was empty, quick return.
if (_commandline.length() == 0)
{
return S_OK;
}
std::vector<std::wstring> args;
auto hr = S_OK;
// Make a mutable copy of the commandline for tokenizing
auto copy = _commandline;
// Tokenize the commandline
auto argc = 0;
wil::unique_hlocal_ptr<PWSTR[]> argv;
argv.reset(CommandLineToArgvW(copy.c_str(), &argc));
RETURN_LAST_ERROR_IF(argv == nullptr);
for (auto i = 1; i < argc; ++i)
{
args.push_back(argv[i]);
}
// Parse args out of the commandline.
// As we handle a token, remove it from the args.
// At the end of parsing, there should be nothing left.
for (size_t i = 0; i < args.size();)
{
hr = E_INVALIDARG;
auto arg = args[i];
if (arg.substr(0, HANDLE_PREFIX.length()) == HANDLE_PREFIX ||
arg == SERVER_HANDLE_ARG)
{
// server handle token accepted two ways:
// --server 0x4 (new method)
// 0x4 (legacy method)
// If we see >1 of these, it's invalid.
auto serverHandleVal = arg;
if (arg == SERVER_HANDLE_ARG)
{
hr = s_GetArgumentValue(args, i, &serverHandleVal);
}
else
{
s_ConsumeArg(args, i);
hr = S_OK;
}
if (SUCCEEDED(hr))
{
hr = s_ParseHandleArg(serverHandleVal, _serverHandle);
if (SUCCEEDED(hr))
{
_createServerHandle = false;
}
}
}
elseif (arg == SIGNAL_HANDLE_ARG)
{
std::wstring signalHandleVal;
hr = s_GetArgumentValue(args, i, &signalHandleVal);
if (SUCCEEDED(hr))
{
hr = s_ParseHandleArg(signalHandleVal, _signalHandle);
}
}
elseif (arg == FORCE_V1_ARG)
{
// -ForceV1 command line switch for NTVDM support
_forceV1 = true;
s_ConsumeArg(args, i);
hr = S_OK;
}
elseif (arg == FORCE_NO_HANDOFF_ARG)
{
// Prevent default application handoff to a different console/terminal
_forceNoHandoff = true;
s_ConsumeArg(args, i);
hr = S_OK;
}
elseif (arg == COM_SERVER_ARG)
{
_runAsComServer = true;
s_ConsumeArg(args, i);
hr = S_OK;
}
elseif (arg.substr(0, FILEPATH_LEADER_PREFIX.length()) == FILEPATH_LEADER_PREFIX)
{
// beginning of command line -- includes file path
// skipped for historical reasons.
s_ConsumeArg(args, i);
hr = S_OK;
}
elseif (arg == WIDTH_ARG)
{
hr = s_GetArgumentValue(args, i, &_width);
}
elseif (arg == HEIGHT_ARG)
{
hr = s_GetArgumentValue(args, i, &_height);
}
elseif (arg == FEATURE_ARG)
{
hr = s_HandleFeatureValue(args, i);
}
elseif (arg == HEADLESS_ARG)
{
_headless = true;
s_ConsumeArg(args, i);
hr = S_OK;
}
elseif (arg == INHERIT_CURSOR_ARG)
{
_inheritCursor = true;
s_ConsumeArg(args, i);
hr = S_OK;
}
elseif (arg == GLYPH_WIDTH)
{
hr = s_GetArgumentValue(args, i, &_textMeasurement);
}
elseif (arg == CLIENT_COMMANDLINE_ARG)
{
// Everything after this is the explicit commandline
hr = _GetClientCommandline(args, i, true);
break;
}
// TODO: handle the rest of the possible params (MSFT:13271366, MSFT:13631640)
// TODO: handle invalid args
// e.g. "conhost --foo bar" should not make the clientCommandline "--foo bar"
else
{
// If we encounter something that doesn't match one of our other
// args, then it's the start of the commandline
hr = _GetClientCommandline(args, i, false);
break;
}
if (FAILED(hr))
{
break;
}
}
// We should have consumed every token at this point.
// if not, it is some sort of parsing error.
// If we failed to parse an arg, then no need to assert.
if (SUCCEEDED(hr))
{
FAIL_FAST_IF(!args.empty());
}
return hr;
}
// Routine Description:
// - Returns true if we already have opened handles to use for the VT server
// streams.
// - If false, try next to see if we have pipe names to open instead.
// Arguments:
// - <none> - uses internal state
// Return Value:
// - True or false (see description)
boolConsoleArguments::HasVtHandles() const
{
returnIsValidHandle(_vtInHandle) && IsValidHandle(_vtOutHandle);
}
// Routine Description:
// - Returns true if we were passed a seemingly valid signal handle on startup.
// Arguments:
// - <none> - uses internal state
// Return Value:
// - True or false (see description)
boolConsoleArguments::HasSignalHandle() const
{
returnIsValidHandle(GetSignalHandle());
}
// Routine Description:
// - Returns true if we already have at least one handle for conpty streams.
// Arguments:
// - <none> - uses internal state
// Return Value:
// - True or false (see description)
boolConsoleArguments::InConptyMode() constnoexcept
{
// If we only have a signal handle, then that's fine, they probably called
// CreatePseudoConsole with neither handle.
// If we only have one of the other handles, that's fine they're still
// invoking us by passing in pipes, so they know what they're doing.
returnIsValidHandle(_vtInHandle) || IsValidHandle(_vtOutHandle) || HasSignalHandle();
}
boolConsoleArguments::IsHeadless() const
{
return _headless;
}
boolConsoleArguments::ShouldCreateServerHandle() const
{
return _createServerHandle;
}
boolConsoleArguments::ShouldRunAsComServer() const
{
return _runAsComServer;
}
HANDLE ConsoleArguments::GetServerHandle() const
{
returnULongToHandle(_serverHandle);
}
HANDLE ConsoleArguments::GetSignalHandle() const
{
returnULongToHandle(_signalHandle);
}
HANDLE ConsoleArguments::GetVtInHandle() const
{
return _vtInHandle;
}
HANDLE ConsoleArguments::GetVtOutHandle() const
{
return _vtOutHandle;
}
std::wstring ConsoleArguments::GetOriginalCommandLine() const
{
return _commandline;
}
std::wstring ConsoleArguments::GetClientCommandline() const
{
return _clientCommandline;
}
const std::wstring& ConsoleArguments::GetTextMeasurement() const
{
return _textMeasurement;
}
boolConsoleArguments::GetForceV1() const
{
return _forceV1;
}
boolConsoleArguments::GetForceNoHandoff() const
{
return _forceNoHandoff;
}
shortConsoleArguments::GetWidth() const
{
return _width;
}
shortConsoleArguments::GetHeight() const
{
return _height;
}
boolConsoleArguments::GetInheritCursor() const
{
return _inheritCursor;
}
#ifdef UNIT_TESTING
// Method Description:
// - This is a test helper method. It can be used to trick us into thinking
// we're in conpty mode, even without parsing any arguments.
// Arguments:
// - <none>
// Return Value:
// - <none>
voidConsoleArguments::EnableConptyModeForTests()
{
_headless = true;
_vtInHandle = GetStdHandle(STD_INPUT_HANDLE);
_vtOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
}
#endif