Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
master
Branches (3)
Tags (3)
master
zadjii-msft-patch-readme
richturn/retarget-echocon
1904.29002
1810.02002
1708.14008
master
Branches (3)
Tags (3)
master
zadjii-msft-patch-readme
richturn/retarget-echocon
1904.29002
1810.02002
1708.14008
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
master
Branches (3)
Tags (3)
master
zadjii-msft-patch-readme
richturn/retarget-echocon
1904.29002
1810.02002
1708.14008
Terminal
/
src
/
host
/
alias.cpp
Terminal
/
src
/
host
/
alias.cpp
alias.cpp 50.60 KB
Copy Edit Raw Blame History
Dustin Howett authored 2019年05月03日 06:29 +08:00 . Initial release of the Windows Terminal source code
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "alias.h"
#include "_output.h"
#include "output.h"
#include "stream.h"
#include "_stream.h"
#include "dbcs.h"
#include "handle.h"
#include "misc.h"
#include "../types/inc/convert.hpp"
#include "srvinit.h"
#include "resource.h"
#include "ApiRoutines.h"
#include "..\interactivity\inc\ServiceLocator.hpp"
#pragma hdrstop
struct case_insensitive_hash
{
std::size_t operator()(const std::wstring& key) const
{
std::wstring lower(key);
std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);
std::hash<std::wstring> hash;
return hash(lower);
}
};
struct case_insensitive_equality
{
bool operator()(const std::wstring& lhs, const std::wstring& rhs) const
{
return 0 == _wcsicmp(lhs.data(), rhs.data());
}
};
std::unordered_map<std::wstring,
std::unordered_map<std::wstring,
std::wstring,
case_insensitive_hash,
case_insensitive_equality>,
case_insensitive_hash,
case_insensitive_equality> g_aliasData;
// Routine Description:
// - Adds a command line alias to the global set.
// - Converts and calls the W version of this function.
// Arguments:
// - source - The shorthand/alias or source buffer to set
// - target- The destination/expansion or target buffer to set
// - exeName - The client EXE application attached to the host to whom this substitution will apply
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::AddConsoleAliasAImpl(const std::string_view source,
const std::string_view target,
const std::string_view exeName) noexcept
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
UINT const codepage = gci.CP;
try
{
const auto sourceW = ConvertToW(codepage, source);
const auto targetW = ConvertToW(codepage, target);
const auto exeNameW = ConvertToW(codepage, exeName);
return AddConsoleAliasWImpl(sourceW, targetW, exeNameW);
}
CATCH_RETURN();
}
// Routine Description:
// - Adds a command line alias to the global set.
// Arguments:
// - source - The shorthand/alias or source buffer to set
// - target - The destination/expansion or target buffer to set
// - exeName - The client EXE application attached to the host to whom this substitution will apply
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::AddConsoleAliasWImpl(const std::wstring_view source,
const std::wstring_view target,
const std::wstring_view exeName) noexcept
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
RETURN_HR_IF(E_INVALIDARG, source.size() == 0);
try
{
std::wstring exeNameString(exeName);
std::wstring sourceString(source);
std::wstring targetString(target);
std::transform(exeNameString.begin(), exeNameString.end(), exeNameString.begin(), towlower);
std::transform(sourceString.begin(), sourceString.end(), sourceString.begin(), towlower);
if (targetString.size() == 0)
{
// Only try to dig in and erase if the exeName exists.
auto exeData = g_aliasData.find(exeNameString);
if (exeData != g_aliasData.end())
{
g_aliasData[exeNameString].erase(sourceString);
}
}
else
{
// Map will auto-create each level as necessary
g_aliasData[exeNameString][sourceString] = targetString;
}
}
CATCH_RETURN();
return S_OK;
}
// Routine Description:
// - Retrieves a command line alias from the global set.
// - It is permitted to call this function without having a target buffer. Use the result to allocate
// the appropriate amount of space and call again.
// - This behavior exists to allow the A version of the function to help allocate the right temp buffer for conversion of
// the output/result data.
// Arguments:
// - source - The shorthand/alias or source buffer to use in lookup
// - target - The destination/expansion or target buffer we are attempting to retrieve. Optionally nullopt to retrieve needed space.
// - writtenOrNeeded - Will specify how many characters were written (if target has value)
// or how many characters would have been consumed (if target is nullopt).
// - exeName - The client EXE application attached to the host whose set we should check
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT GetConsoleAliasWImplHelper(const std::wstring_view source,
std::optional<gsl::span<wchar_t>> target,
size_t& writtenOrNeeded,
const std::wstring_view exeName)
{
// Ensure output variables are initialized
writtenOrNeeded = 0;
if (target.has_value() && target.value().size() > 0)
{
target.value().at(0) = UNICODE_NULL;
}
std::wstring exeNameString(exeName);
std::wstring sourceString(source);
// For compatibility, return ERROR_GEN_FAILURE for any result where the alias can't be found.
// We use .find for the iterators then dereference to search without creating entries.
const auto exeIter = g_aliasData.find(exeNameString);
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_GEN_FAILURE), exeIter == g_aliasData.end());
const auto exeData = exeIter->second;
const auto sourceIter = exeData.find(sourceString);
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_GEN_FAILURE), sourceIter == exeData.end());
const auto targetString = sourceIter->second;
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_GEN_FAILURE), targetString.size() == 0);
// TargetLength is a byte count, convert to characters.
size_t targetSize = targetString.size();
size_t const cchNull = 1;
// The total space we need is the length of the string + the null terminator.
size_t neededSize;
RETURN_IF_FAILED(SizeTAdd(targetSize, cchNull, &neededSize));
writtenOrNeeded = neededSize;
if (target.has_value())
{
// if the user didn't give us enough space, return with insufficient buffer code early.
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), gsl::narrow<size_t>(target.value().size()) < neededSize);
RETURN_IF_FAILED(StringCchCopyNW(target.value().data(), target.value().size(), targetString.data(), targetSize));
}
return S_OK;
}
// Routine Description:
// - Retrieves a command line alias from the global set.
// - This function will convert input parameters from A to W, call the W version of the routine,
// and attempt to convert the resulting data back to A for return.
// Arguments:
// - source - The shorthand/alias or source buffer to use in lookup
// - target - The destination/expansion or target buffer we are attempting to retrieve.
// - written - Will specify how many characters were written
// - exeName - The client EXE application attached to the host whose set we should check
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasAImpl(const std::string_view source,
gsl::span<char> target,
size_t& written,
const std::string_view exeName) noexcept
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
UINT const codepage = gci.CP;
// Ensure output variables are initialized
written = 0;
try
{
if (target.size() > 0)
{
target.at(0) = ANSI_NULL;
}
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// Convert our input parameters to Unicode.
const auto sourceW = ConvertToW(codepage, source);
const auto exeNameW = ConvertToW(codepage, exeName);
// Figure out how big our temporary Unicode buffer must be to retrieve output
size_t targetNeeded;
RETURN_IF_FAILED(GetConsoleAliasWImplHelper(sourceW, std::nullopt, targetNeeded, exeNameW));
// If there's nothing to get, then simply return.
RETURN_HR_IF(S_OK, 0 == targetNeeded);
// If the user hasn't given us a buffer at all and we need one, return an error.
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), 0 == target.size());
// Allocate a unicode buffer of the right size.
std::unique_ptr<wchar_t[]> targetBuffer = std::make_unique<wchar_t[]>(targetNeeded);
RETURN_IF_NULL_ALLOC(targetBuffer);
// Call the Unicode version of this method
size_t targetWritten;
RETURN_IF_FAILED(GetConsoleAliasWImplHelper(sourceW,
gsl::span<wchar_t>(targetBuffer.get(), targetNeeded),
targetWritten,
exeNameW));
// Set the return size copied to the size given before we attempt to copy.
// Then multiply by sizeof(wchar_t) due to a long standing bug that we must preserve for compatibility.
// On failure, the API has historically given back this value.
written = target.size() * sizeof(wchar_t);
// Convert result to A
const auto converted = ConvertToA(codepage, { targetBuffer.get(), targetWritten });
// Copy safely to output buffer
RETURN_IF_FAILED(StringCchCopyNA(target.data(), target.size(), converted.data(), converted.size()));
// And return the size copied.
written = converted.size();
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves a command line alias from the global set.
// Arguments:
// - source - The shorthand/alias or source buffer to use in lookup
// - target - The destination/expansion or target buffer we are attempting to retrieve.
// - written - Will specify how many characters were written
// - exeName - The client EXE application attached to the host whose set we should check
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasWImpl(const std::wstring_view source,
gsl::span<wchar_t> target,
size_t& written,
const std::wstring_view exeName) noexcept
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
try
{
HRESULT hr = GetConsoleAliasWImplHelper(source, target, written, exeName);
if (FAILED(hr))
{
written = target.size();
}
return hr;
}
CATCH_RETURN();
}
// These variables define the seperator character and the length of the string.
// They will be used to as the joiner between source and target strings when returning alias data in list form.
static std::wstring aliasesSeparator(L"=");
// Routine Description:
// - Retrieves the amount of space needed to hold all aliases (source=target pairs) for the given EXE name
// - Works for both Unicode and Multibyte text.
// - This method configuration is called for both A/W routines to allow us an efficient way of asking the system
// the lengths of how long each conversion would be without actually performing the full allocations/conversions.
// Arguments:
// - exeName - The client EXE application attached to the host whose set we should check
// - countInUnicode - True for W version (UTF-16 Unicode) calls. False for A version calls (all multibyte formats.)
// - codepage - Set to valid Windows Codepage for A version calls. Ignored for W (but typically just set to 0.)
// - bufferRequired - Receives the length of buffer that would be required to retrieve all aliases for the given exe.
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT GetConsoleAliasesLengthWImplHelper(const std::wstring_view exeName,
const bool countInUnicode,
const UINT codepage,
size_t& bufferRequired)
{
// Ensure output variables are initialized
bufferRequired = 0;
try
{
const std::wstring exeNameString(exeName);
size_t cchNeeded = 0;
// Each of the aliases will be made up of the source, a seperator, the target, then a null character.
// They are of the form "Source=Target" when returned.
size_t const cchNull = 1;
size_t cchSeperator = aliasesSeparator.size();
// If we're counting how much multibyte space will be needed, trial convert the seperator before we add.
if (!countInUnicode)
{
cchSeperator = GetALengthFromW(codepage, aliasesSeparator);
}
// Find without creating.
auto exeIter = g_aliasData.find(exeNameString);
if (exeIter != g_aliasData.end())
{
auto list = exeIter->second;
for (auto& pair : list)
{
// Alias stores lengths in bytes.
size_t cchSource = pair.first.size();
size_t cchTarget = pair.second.size();
// If we're counting how much multibyte space will be needed, trial convert the source and target strings before we add.
if (!countInUnicode)
{
cchSource = GetALengthFromW(codepage, pair.first);
cchTarget = GetALengthFromW(codepage, pair.second);
}
// Accumulate all sizes to the final string count.
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchSource, &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchSeperator, &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchTarget, &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchNull, &cchNeeded));
}
}
bufferRequired = cchNeeded;
}
CATCH_RETURN();
return S_OK;
}
// Routine Description:
// - Retrieves the amount of space needed to hold all aliases (source=target pairs) for the given EXE name
// - Converts input text from A to W then makes the call to the W implementation.
// Arguments:
// - exeName - The client EXE application attached to the host whose set we should check
// - bufferRequired - Receives the length of buffer that would be required to retrieve all aliases for the given exe.
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasesLengthAImpl(const std::string_view exeName,
size_t& bufferRequired) noexcept
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
UINT const codepage = gci.CP;
// Ensure output variables are initialized
bufferRequired = 0;
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// Convert our input parameters to Unicode
try
{
const auto exeNameW = ConvertToW(codepage, exeName);
return GetConsoleAliasesLengthWImplHelper(exeNameW, false, codepage, bufferRequired);
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves the amount of space needed to hold all aliases (source=target pairs) for the given EXE name
// - Converts input text from A to W then makes the call to the W implementation.
// Arguments:
// - exeName - The client EXE application attached to the host whose set we should check
// - bufferRequired - Receives the length of buffer that would be required to retrieve all aliases for the given exe.
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasesLengthWImpl(const std::wstring_view exeName,
size_t& bufferRequired) noexcept
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
try
{
return GetConsoleAliasesLengthWImplHelper(exeName, true, 0, bufferRequired);
}
CATCH_RETURN();
}
// Routine Description:
// - Clears all aliases on CMD.exe.
void Alias::s_ClearCmdExeAliases()
{
// find without creating.
auto exeIter = g_aliasData.find(L"cmd.exe");
if (exeIter != g_aliasData.end())
{
exeIter->second.clear();
}
}
// Routine Description:
// - Retrieves all source=target pairs representing alias definitions for a given EXE name
// - It is permitted to call this function without having a target buffer. Use the result to allocate
// the appropriate amount of space and call again.
// - This behavior exists to allow the A version of the function to help allocate the right temp buffer for conversion of
// the output/result data.
// Arguments:
// - exeName - The client EXE application attached to the host whose set we should check
// - aliasBuffer - The target buffer to hold all alias pairs we are trying to retrieve.
// Optionally nullopt to retrieve needed space.
// - writtenOrNeeded - Pointer to space that will specify how many characters were written (if buffer is valid)
// or how many characters would have been needed (if buffer is nullopt).
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT GetConsoleAliasesWImplHelper(const std::wstring_view exeName,
std::optional<gsl::span<wchar_t>> aliasBuffer,
size_t& writtenOrNeeded)
{
// Ensure output variables are initialized.
writtenOrNeeded = 0;
if (aliasBuffer.has_value() && aliasBuffer.value().size() > 0)
{
aliasBuffer.value().at(0) = UNICODE_NULL;
}
std::wstring exeNameString(exeName);
LPWSTR AliasesBufferPtrW = aliasBuffer.has_value() ? aliasBuffer.value().data() : nullptr;
size_t cchTotalLength = 0; // accumulate the characters we need/have copied as we walk the list
// Each of the alises will be made up of the source, a seperator, the target, then a null character.
// They are of the form "Source=Target" when returned.
size_t const cchNull = 1;
// Find without creating.
auto exeIter = g_aliasData.find(exeNameString);
if (exeIter != g_aliasData.end())
{
auto list = exeIter->second;
for (auto& pair : list)
{
// Alias stores lengths in bytes.
size_t const cchSource = pair.first.size();
size_t const cchTarget = pair.second.size();
// Add up how many characters we will need for the full alias data.
size_t cchNeeded = 0;
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchSource, &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, aliasesSeparator.size(), &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchTarget, &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchNull, &cchNeeded));
// If we can return the data, attempt to do so until we're done or it overflows.
// If we cannot return data, we're just going to loop anyway and count how much space we'd need.
if (aliasBuffer.has_value())
{
// Calculate the new final total after we add what we need to see if it will exceed the limit
size_t cchNewTotal;
RETURN_IF_FAILED(SizeTAdd(cchTotalLength, cchNeeded, &cchNewTotal));
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW), cchNewTotal > gsl::narrow<size_t>(aliasBuffer.value().size()));
size_t cchAliasBufferRemaining;
RETURN_IF_FAILED(SizeTSub(aliasBuffer.value().size(), cchTotalLength, &cchAliasBufferRemaining));
RETURN_IF_FAILED(StringCchCopyNW(AliasesBufferPtrW, cchAliasBufferRemaining, pair.first.data(), cchSource));
RETURN_IF_FAILED(SizeTSub(cchAliasBufferRemaining, cchSource, &cchAliasBufferRemaining));
AliasesBufferPtrW += cchSource;
RETURN_IF_FAILED(StringCchCopyNW(AliasesBufferPtrW, cchAliasBufferRemaining, aliasesSeparator.data(), aliasesSeparator.size()));
RETURN_IF_FAILED(SizeTSub(cchAliasBufferRemaining, aliasesSeparator.size(), &cchAliasBufferRemaining));
AliasesBufferPtrW += aliasesSeparator.size();
RETURN_IF_FAILED(StringCchCopyNW(AliasesBufferPtrW, cchAliasBufferRemaining, pair.second.data(), cchTarget));
RETURN_IF_FAILED(SizeTSub(cchAliasBufferRemaining, cchTarget, &cchAliasBufferRemaining));
AliasesBufferPtrW += cchTarget;
// StringCchCopyNW ensures that the destination string is null terminated, so simply advance the pointer.
RETURN_IF_FAILED(SizeTSub(cchAliasBufferRemaining, 1, &cchAliasBufferRemaining));
AliasesBufferPtrW += cchNull;
}
RETURN_IF_FAILED(SizeTAdd(cchTotalLength, cchNeeded, &cchTotalLength));
}
}
writtenOrNeeded = cchTotalLength;
return S_OK;
}
// Routine Description:
// - Retrieves all source=target pairs representing alias definitions for a given EXE name
// - Will convert all input from A to W, call the W version of the function, then convert resulting W to A text and return.
// Arguments:
// - exeName - The client EXE application attached to the host whose set we should check
// - alias - The target buffer to hold all alias pairs we are trying to retrieve.
// - written - Will specify how many characters were written
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasesAImpl(const std::string_view exeName,
gsl::span<char> alias,
size_t& written) noexcept
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
UINT const codepage = gci.CP;
// Ensure output variables are initialized
written = 0;
try
{
if (alias.size() > 0)
{
alias.at(0) = '0円';
}
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// Convert our input parameters to Unicode.
const auto exeNameW = ConvertToW(codepage, exeName);
wistd::unique_ptr<wchar_t[]> pwsExeName;
// Figure out how big our temporary Unicode buffer must be to retrieve output
size_t bufferNeeded;
RETURN_IF_FAILED(GetConsoleAliasesWImplHelper(exeNameW, std::nullopt, bufferNeeded));
// If there's nothing to get, then simply return.
RETURN_HR_IF(S_OK, 0 == bufferNeeded);
// Allocate a unicode buffer of the right size.
std::unique_ptr<wchar_t[]> aliasBuffer = std::make_unique<wchar_t[]>(bufferNeeded);
RETURN_IF_NULL_ALLOC(aliasBuffer);
// Call the Unicode version of this method
size_t bufferWritten;
RETURN_IF_FAILED(GetConsoleAliasesWImplHelper(exeNameW, gsl::span<wchar_t>(aliasBuffer.get(), bufferNeeded), bufferWritten));
// Convert result to A
const auto converted = ConvertToA(codepage, { aliasBuffer.get(), bufferWritten });
// Copy safely to the output buffer
// - Aliases are a series of null terminated strings. We cannot use a SafeString function to copy.
// So instead, validate and use raw memory copy.
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW), converted.size() > gsl::narrow<size_t>(alias.size()));
memcpy_s(alias.data(), alias.size(), converted.data(), converted.size());
// And return the size copied.
written = converted.size();
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves all source=target pairs representing alias definitions for a given EXE name
// Arguments:
// - exeName - The client EXE application attached to the host whose set we should check
// - alias - The target buffer to hold all alias pairs we are trying to retrieve.
// - written - Will specify how many characters were written
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasesWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> alias,
size_t& written) noexcept
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
try
{
return GetConsoleAliasesWImplHelper(exeName, alias, written);
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves the amount of space needed to hold all EXE names with aliases defined that are known to the console
// - Works for both Unicode and Multibyte text.
// - This method configuration is called for both A/W routines to allow us an efficient way of asking the system
// the lengths of how long each conversion would be without actually performing the full allocations/conversions.
// Arguments:
// - countInUnicode - True for W version (UCS-2 Unicode) calls. False for A version calls (all multibyte formats.)
// - codepage - Set to valid Windows Codepage for A version calls. Ignored for W (but typically just set to 0.)
// - bufferRequired - Receives the length of buffer that would be required to retrieve all relevant EXE names.
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT GetConsoleAliasExesLengthImplHelper(const bool countInUnicode, const UINT codepage, size_t& bufferRequired)
{
// Ensure output variables are initialized
bufferRequired = 0;
size_t cchNeeded = 0;
// Each alias exe will be made up of the string payload and a null terminator.
size_t const cchNull = 1;
for (auto& pair : g_aliasData)
{
size_t cchExe = pair.first.size();
// If we're counting how much multibyte space will be needed, trial convert the exe string before we add.
if (!countInUnicode)
{
cchExe = GetALengthFromW(codepage, pair.first);
}
// Accumulate to total
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchExe, &cchNeeded));
RETURN_IF_FAILED(SizeTAdd(cchNeeded, cchNull, &cchNeeded));
}
bufferRequired = cchNeeded;
return S_OK;
}
// Routine Description:
// - Retrieves the amount of space needed to hold all EXE names with aliases defined that are known to the console
// Arguments:
// - bufferRequired - Receives the length of buffer that would be required to retrieve all relevant EXE names.
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept
{
LockConsole();
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
return GetConsoleAliasExesLengthImplHelper(false, gci.CP, bufferRequired);
}
// Routine Description:
// - Retrieves the amount of space needed to hold all EXE names with aliases defined that are known to the console
// Arguments:
// - bufferRequired - Pointer to receive the length of buffer that would be required to retrieve all relevant EXE names.
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
return GetConsoleAliasExesLengthImplHelper(true, 0, bufferRequired);
}
// Routine Description:
// - Retrieves all EXE names with aliases defined that are known to the console.
// - It is permitted to call this function without having a target buffer. Use the result to allocate
// the appropriate amount of space and call again.
// - This behavior exists to allow the A version of the function to help allocate the right temp buffer for conversion of
// the output/result data.
// Arguments:
// - pwsAliasExesBuffer - The target buffer to hold all known EXE names we are trying to retrieve.
// Optionally nullopt to retrieve needed space.
// - cchAliasExesBufferLength - Length in characters of target buffer. Set to 0 when buffer is nullptr.
// - pcchAliasExesBufferWrittenOrNeeded - Pointer to space that will specify how many characters were written (if buffer is valid)
// or how many characters would have been needed (if buffer is nullopt).
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT GetConsoleAliasExesWImplHelper(std::optional<gsl::span<wchar_t>> aliasExesBuffer,
size_t& writtenOrNeeded)
{
// Ensure output variables are initialized.
writtenOrNeeded = 0;
if (aliasExesBuffer.has_value() && aliasExesBuffer.value().size() > 0)
{
aliasExesBuffer.value().at(0) = UNICODE_NULL;
}
LPWSTR AliasExesBufferPtrW = aliasExesBuffer.has_value() ? aliasExesBuffer.value().data() : nullptr;
size_t cchTotalLength = 0; // accumulate the characters we need/have copied as we walk the list
size_t const cchNull = 1;
for (auto& pair : g_aliasData)
{
// AliasList stores length in bytes. Add 1 for null terminator.
size_t const cchExe = pair.first.size();
size_t cchNeeded;
RETURN_IF_FAILED(SizeTAdd(cchExe, cchNull, &cchNeeded));
// If we can return the data, attempt to do so until we're done or it overflows.
// If we cannot return data, we're just going to loop anyway and count how much space we'd need.
if (aliasExesBuffer.has_value())
{
// Calculate the new total length after we add to the buffer
// Error out early if there is a problem.
size_t cchNewTotal;
RETURN_IF_FAILED(SizeTAdd(cchTotalLength, cchNeeded, &cchNewTotal));
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW), cchNewTotal > gsl::narrow<size_t>(aliasExesBuffer.value().size()));
size_t cchRemaining;
RETURN_IF_FAILED(SizeTSub(aliasExesBuffer.value().size(), cchTotalLength, &cchRemaining));
RETURN_IF_FAILED(StringCchCopyNW(AliasExesBufferPtrW, cchRemaining, pair.first.data(), cchExe));
AliasExesBufferPtrW += cchNeeded;
}
// Accumulate the total written amount.
RETURN_IF_FAILED(SizeTAdd(cchTotalLength, cchNeeded, &cchTotalLength));
}
writtenOrNeeded = cchTotalLength;
return S_OK;
}
// Routine Description:
// - Retrieves all EXE names with aliases defined that are known to the console.
// - Will call the W version of the function and convert all text back to A on returning.
// Arguments:
// - aliasExes - The target buffer to hold all known EXE names we are trying to retrieve.
// - written - Specifies how many characters were written
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasExesAImpl(gsl::span<char> aliasExes,
size_t& written) noexcept
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
UINT const codepage = gci.CP;
// Ensure output variables are initialized
written = 0;
try
{
if (aliasExes.size() > 0)
{
aliasExes.at(0) = '0円';
}
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// Figure our how big our temporary Unicode buffer must be to retrieve output
size_t bufferNeeded;
RETURN_IF_FAILED(GetConsoleAliasExesWImplHelper(std::nullopt, bufferNeeded));
// If there's nothing to get, then simply return.
RETURN_HR_IF(S_OK, 0 == bufferNeeded);
// Allocate a unicode buffer of the right size.
std::unique_ptr<wchar_t[]> targetBuffer = std::make_unique<wchar_t[]>(bufferNeeded);
RETURN_IF_NULL_ALLOC(targetBuffer);
// Call the Unicode version of this method
size_t bufferWritten;
RETURN_IF_FAILED(GetConsoleAliasExesWImplHelper(gsl::span<wchar_t>(targetBuffer.get(), bufferNeeded), bufferWritten));
// Convert result to A
const auto converted = ConvertToA(codepage, { targetBuffer.get(), bufferWritten });
// Copy safely to the output buffer
// - AliasExes are a series of null terminated strings. We cannot use a SafeString function to copy.
// So instead, validate and use raw memory copy.
RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW), converted.size() > gsl::narrow<size_t>(aliasExes.size()));
memcpy_s(aliasExes.data(), aliasExes.size(), converted.data(), converted.size());
// And return the size copied.
written = converted.size();
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves all EXE names with aliases defined that are known to the console.
// Arguments:
// - pwsAliasExesBuffer - The target buffer to hold all known EXE names we are trying to retrieve.
// - cchAliasExesBufferLength - Length in characters of target buffer. Set to 0 when buffer is nullptr.
// - pcchAliasExesBufferWrittenOrNeeded - Pointer to space that will specify how many characters were written
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]]
HRESULT ApiRoutines::GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes,
size_t& written) noexcept
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
try
{
return GetConsoleAliasExesWImplHelper(aliasExes, written);
}
CATCH_RETURN();
}
// Routine Description:
// - Trims leading spaces off of a string
// Arguments:
// - str - String to trim
void Alias::s_TrimLeadingSpaces(std::wstring& str)
{
// Erase from the beginning of the string up until the first
// character found that is not a space.
str.erase(str.begin(),
std::find_if(str.begin(), str.end(), [](wchar_t ch) { return !std::iswspace(ch); }));
}
// Routine Description:
// - Trims trailing \r\n off of a string
// Arguments:
// - str - String to trim
void Alias::s_TrimTrailingCrLf(std::wstring& str)
{
const auto trailingCrLfPos = str.find_last_of(UNICODE_CARRIAGERETURN);
if (std::wstring::npos != trailingCrLfPos)
{
str.erase(trailingCrLfPos);
}
}
// Routine Description:
// - Tokenizes a string into a collection using space as a separator
// Arguments:
// - str - String to tokenize
// Return Value:
// - Collection of tokenized strings
std::deque<std::wstring> Alias::s_Tokenize(const std::wstring& str)
{
std::deque<std::wstring> result;
size_t prevIndex = 0;
auto spaceIndex = str.find(L' ');
while (std::wstring::npos != spaceIndex)
{
const auto length = spaceIndex - prevIndex;
result.emplace_back(str.substr(prevIndex, length));
spaceIndex++;
prevIndex = spaceIndex;
spaceIndex = str.find(L' ', spaceIndex);
}
// Place the final one into the set.
result.emplace_back(str.substr(prevIndex));
return result;
}
// Routine Description:
// - Gets just the arguments portion of the command string
// Specifically, all text after the first space character.
// Arguments:
// - str - String to split into just args
// Return Value:
// - Only the arguments part of the string or empty if there are no arguments.
std::wstring Alias::s_GetArgString(const std::wstring& str)
{
std::wstring result;
auto firstSpace = str.find_first_of(L' ');
if (std::wstring::npos != firstSpace)
{
firstSpace++;
if (firstSpace < str.size())
{
result = str.substr(firstSpace);
}
}
return result;
}
// Routine Description:
// - Checks the given character to see if it is a numbered arg replacement macro
// and replaces it with the counted argument if there is a match
// Arguments:
// - ch - Character to test as a macro
// - appendToStr - Append the macro result here if it matched
// - tokens - Tokens of the original command string. 0 is alias. 1-N are arguments.
// Return Value:
// - True if we found the macro and appended to the string.
// - False if the given character doesn't match this macro.
bool Alias::s_TryReplaceNumberedArgMacro(const wchar_t ch,
std::wstring& appendToStr,
const std::deque<std::wstring>& tokens)
{
if (ch >= L'1' && ch <= L'9')
{
// Numerical macros substitute that numbered argument
const size_t index = ch - L'0';
if (index < tokens.size() && index > 0)
{
appendToStr.append(tokens[index]);
}
return true;
}
return false;
}
// Routine Description:
// - Checks the given character to see if it is a wildcard arg replacement macro
// and replaces it with the entire argument string if there is a match
// Arguments:
// - ch - Character to test as a macro
// - appendToStr - Append the macro result here if it matched
// - fullArgString - All of the arguments as one big string.
// Return Value:
// - True if we found the macro and appended to the string.
// - False if the given character doesn't match this macro.
bool Alias::s_TryReplaceWildcardArgMacro(const wchar_t ch,
std::wstring& appendToStr,
const std::wstring fullArgString)
{
if (L'*' == ch)
{
// Wildcard substitutes all arguments
appendToStr.append(fullArgString);
return true;
}
return false;
}
// Routine Description:
// - Checks the given character to see if it is an input redirection macro
// and replaces it with the < redirector if there is a match
// Arguments:
// - ch - Character to test as a macro
// - appendToStr - Append the macro result here if it matched
// Return Value:
// - True if we found the macro and appended to the string.
// - False if the given character doesn't match this macro.
bool Alias::s_TryReplaceInputRedirMacro(const wchar_t ch,
std::wstring& appendToStr)
{
if (L'L' == towupper(ch))
{
// L (either case) replaces with input redirector <
appendToStr.push_back(L'<');
return true;
}
return false;
}
// Routine Description:
// - Checks the given character to see if it is an output redirection macro
// and replaces it with the > redirector if there is a match
// Arguments:
// - ch - Character to test as a macro
// - appendToStr - Append the macro result here if it matched
// Return Value:
// - True if we found the macro and appended to the string.
// - False if the given character doesn't match this macro.
bool Alias::s_TryReplaceOutputRedirMacro(const wchar_t ch,
std::wstring& appendToStr)
{
if (L'G' == towupper(ch))
{
// G (either case) replaces with output redirector >
appendToStr.push_back(L'>');
return true;
}
return false;
}
// Routine Description:
// - Checks the given character to see if it is a pipe redirection macro
// and replaces it with the | redirector if there is a match
// Arguments:
// - ch - Character to test as a macro
// - appendToStr - Append the macro result here if it matched
// Return Value:
// - True if we found the macro and appended to the string.
// - False if the given character doesn't match this macro.
bool Alias::s_TryReplacePipeRedirMacro(const wchar_t ch,
std::wstring& appendToStr)
{
if (L'B' == towupper(ch))
{
// B (either case) replaces with pipe operator |
appendToStr.push_back(L'|');
return true;
}
return false;
}
// Routine Description:
// - Checks the given character to see if it is a next command macro
// and replaces it with CRLF if there is a match
// Arguments:
// - ch - Character to test as a macro
// - appendToStr - Append the macro result here if it matched
// - lineCount - Updates the rolling count of lines if we add a CRLF.
// Return Value:
// - True if we found the macro and appended to the string.
// - False if the given character doesn't match this macro.
bool Alias::s_TryReplaceNextCommandMacro(const wchar_t ch,
std::wstring& appendToStr,
size_t& lineCount)
{
if (L'T' == towupper(ch))
{
// T (either case) inserts a CRLF to chain commands
s_AppendCrLf(appendToStr, lineCount);
return true;
}
return false;
}
// Routine Description:
// - Appends the system line feed (CRLF) to the given string
// Arguments:
// - appendToStr - Append the system line feed here
// - lineCount - Updates the rolling count of lines if we add a CRLF.
void Alias::s_AppendCrLf(std::wstring& appendToStr,
size_t& lineCount)
{
appendToStr.push_back(L'\r');
appendToStr.push_back(L'\n');
lineCount++;
}
// Routine Description:
// - Searches through the given string for macros and replaces them
// with the matching action
// Arguments:
// - str - On input, the string to search. On output, the string is replaced.
// - tokens - The tokenized command line input. 0 is the alias, 1-N are arguments.
// - fullArgString - Shorthand to 1-N argument string in case of wildcard match.
// Return Value:
// - The number of commands in the final string (line feeds, CRLFs)
size_t Alias::s_ReplaceMacros(std::wstring& str,
const std::deque<std::wstring>& tokens,
const std::wstring& fullArgString)
{
size_t lineCount = 0;
std::wstring finalText;
// The target text may contain substitution macros indicated by $.
// Walk through and substitute them as appropriate.
for (auto ch = str.cbegin(); ch < str.cend(); ch++)
{
if (L'$' == *ch)
{
// Attempt to read ahead by one character.
const auto chNext = ch + 1;
if (chNext < str.cend())
{
auto isProcessed = s_TryReplaceNumberedArgMacro(*chNext, finalText, tokens);
if (!isProcessed)
{
isProcessed = s_TryReplaceWildcardArgMacro(*chNext, finalText, fullArgString);
}
if (!isProcessed)
{
isProcessed = s_TryReplaceInputRedirMacro(*chNext, finalText);
}
if (!isProcessed)
{
isProcessed = s_TryReplaceOutputRedirMacro(*chNext, finalText);
}
if (!isProcessed)
{
isProcessed = s_TryReplacePipeRedirMacro(*chNext, finalText);
}
if (!isProcessed)
{
isProcessed = s_TryReplaceNextCommandMacro(*chNext, finalText, lineCount);
}
if (!isProcessed)
{
// If nothing matches, just push these two characters in.
finalText.push_back(*ch);
finalText.push_back(*chNext);
}
// Since we read ahead and used that character,
// advance the iterator one extra to compensate.
ch++;
}
else
{
// If no read-ahead, just push this character and be done.
finalText.push_back(*ch);
}
}
else
{
// If it didn't match the macro specifier ,ドル push the character.
finalText.push_back(*ch);
}
}
// We always terminate with a CRLF to symbolize end of command.
s_AppendCrLf(finalText, lineCount);
// Give back the final text and count.
str.swap(finalText);
return lineCount;
}
// Routine Description:
// - Takes the source text and searches it for an alias belonging to exe name's list.
// Arguments:
// - sourceText - The string to search for an alias
// - exeName - The name of the EXE that has aliases associated
// - lineCount - Number of lines worth of text processed.
// Return Value:
// - If we found a matching alias, this will be the processed data
// and lineCount is updated to the new number of lines.
// - If we didn't match and process an alias, return an empty string.
std::wstring Alias::s_MatchAndCopyAlias(const std::wstring& sourceText,
const std::wstring& exeName,
size_t& lineCount)
{
// Copy source text into a local for manipulation.
std::wstring sourceCopy(sourceText);
// Trim trailing \r\n off of sourceCopy if it has one.
s_TrimTrailingCrLf(sourceCopy);
// Trim leading spaces off of sourceCopy if it has any.
s_TrimLeadingSpaces(sourceCopy);
// Check if we have an EXE in the list that matches the request first.
auto exeIter = g_aliasData.find(exeName);
if (exeIter == g_aliasData.end())
{
// We found no data for this exe. Give back an empty string.
return std::wstring();
}
auto exeList = exeIter->second;
if (exeList.size() == 0)
{
// If there's no match, give back an empty string.
return std::wstring();
}
// Tokenize the text by spaces
const auto tokens = s_Tokenize(sourceCopy);
// If there are no tokens, return an empty string
if (tokens.size() == 0)
{
return std::wstring();
}
// Find alias. If there isn't one, return an empty string
const auto alias = tokens.front();
const auto aliasIter = exeList.find(alias);
if (aliasIter == exeList.end())
{
// We found no alias pair with this name. Give back an empty string.
return std::wstring();
}
const auto target = aliasIter->second;
if (target.size() == 0)
{
return std::wstring();
}
// Get the string of all parameters as a shorthand for $* later.
const auto allParams = s_GetArgString(sourceCopy);
// The final text will be the target but with macros replaced.
std::wstring finalText(target);
lineCount = s_ReplaceMacros(finalText, tokens, allParams);
return finalText;
}
// Routine Description:
// - This routine matches the input string with an alias and copies the alias to the input buffer.
// Arguments:
// - pwchSource - string to match
// - cbSource - length of pwchSource in bytes
// - pwchTarget - where to store matched string
// - cbTargetSize - on input, contains size of pwchTarget.
// - cbTargetWritten - On output, contains length of alias stored in pwchTarget.
// - pwchExe - Name of exe that command is associated with to find related aliases
// - cbExe - Length in bytes of exe name
// - LineCount - aliases can contain multiple commands. $T is the command separator
// Return Value:
// - None. It will just maintain the source as the target if we can't match an alias.
void Alias::s_MatchAndCopyAliasLegacy(_In_reads_bytes_(cbSource) PWCHAR pwchSource,
_In_ size_t cbSource,
_Out_writes_bytes_(cbTargetWritten) PWCHAR pwchTarget,
_In_ const size_t cbTargetSize,
size_t& cbTargetWritten,
const std::wstring& exeName,
DWORD& lines)
{
try
{
std::wstring sourceText(pwchSource, cbSource / sizeof(WCHAR));
size_t lineCount = lines;
const auto targetText = s_MatchAndCopyAlias(sourceText, exeName, lineCount);
// Only return data if the reply was non-empty (we had a match).
if (!targetText.empty())
{
const auto cchTargetSize = cbTargetSize / sizeof(wchar_t);
// If the target text will fit in the result buffer, fill out the results.
if (targetText.size() <= cchTargetSize)
{
// Non-null terminated copy into memory space
std::copy_n(targetText.data(), targetText.size(), pwchTarget);
// Return bytes copied.
cbTargetWritten = gsl::narrow<ULONG>(targetText.size() * sizeof(wchar_t));
// Return lines info.
lines = gsl::narrow<DWORD>(lineCount);
}
}
}
catch (...)
{
LOG_HR(wil::ResultFromCaughtException());
}
}
#ifdef UNIT_TESTING
void Alias::s_TestAddAlias(std::wstring& exe,
std::wstring& alias,
std::wstring& target)
{
g_aliasData[exe][alias] = target;
}
void Alias::s_TestClearAliases()
{
g_aliasData.clear();
}
#endif
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

About

The new Windows Terminal, and the original Windows console host -- all in the same place!
Cancel

Releases

No release

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/AbstractFactory/Terminal.git
git@gitee.com:AbstractFactory/Terminal.git
AbstractFactory
Terminal
Terminal
master
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /