cmStringCommand.cxx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  4. #define _SCL_SECURE_NO_WARNINGS
  5. #include "cmStringCommand.h"
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <limits>
  10. #include <memory>
  11. #include <stdexcept>
  12. #include <utility>
  13. #include <cm/iterator>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #include <cmext/string_view>
  17. #include <cm3p/json/reader.h>
  18. #include <cm3p/json/value.h>
  19. #include <cm3p/json/writer.h>
  20. #include "cmsys/RegularExpression.hxx"
  21. #include "cmCryptoHash.h"
  22. #include "cmExecutionStatus.h"
  23. #include "cmGeneratorExpression.h"
  24. #include "cmMakefile.h"
  25. #include "cmMessageType.h"
  26. #include "cmPolicies.h"
  27. #include "cmRange.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmStringReplaceHelper.h"
  30. #include "cmSubcommandTable.h"
  31. #include "cmSystemTools.h"
  32. #include "cmTimestamp.h"
  33. #include "cmUuid.h"
  34. #include "cmValue.h"
  35. namespace {
  36. bool RegexMatch(std::vector<std::string> const& args,
  37. cmExecutionStatus& status);
  38. bool RegexMatchAll(std::vector<std::string> const& args,
  39. cmExecutionStatus& status);
  40. bool RegexReplace(std::vector<std::string> const& args,
  41. cmExecutionStatus& status);
  42. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  43. size_t varIdx, cmMakefile& makefile);
  44. bool HandleHashCommand(std::vector<std::string> const& args,
  45. cmExecutionStatus& status)
  46. {
  47. if (args.size() != 3) {
  48. status.SetError(
  49. cmStrCat(args[0], " requires an output variable and an input string"));
  50. return false;
  51. }
  52. std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0]));
  53. if (hash) {
  54. std::string out = hash->HashString(args[2]);
  55. status.GetMakefile().AddDefinition(args[1], out);
  56. return true;
  57. }
  58. return false;
  59. }
  60. bool HandleToUpperLowerCommand(std::vector<std::string> const& args,
  61. bool toUpper, cmExecutionStatus& status)
  62. {
  63. if (args.size() < 3) {
  64. status.SetError("no output variable specified");
  65. return false;
  66. }
  67. std::string const& outvar = args[2];
  68. std::string output;
  69. if (toUpper) {
  70. output = cmSystemTools::UpperCase(args[1]);
  71. } else {
  72. output = cmSystemTools::LowerCase(args[1]);
  73. }
  74. // Store the output in the provided variable.
  75. status.GetMakefile().AddDefinition(outvar, output);
  76. return true;
  77. }
  78. bool HandleToUpperCommand(std::vector<std::string> const& args,
  79. cmExecutionStatus& status)
  80. {
  81. return HandleToUpperLowerCommand(args, true, status);
  82. }
  83. bool HandleToLowerCommand(std::vector<std::string> const& args,
  84. cmExecutionStatus& status)
  85. {
  86. return HandleToUpperLowerCommand(args, false, status);
  87. }
  88. bool HandleAsciiCommand(std::vector<std::string> const& args,
  89. cmExecutionStatus& status)
  90. {
  91. if (args.size() < 3) {
  92. status.SetError("No output variable specified");
  93. return false;
  94. }
  95. std::string::size_type cc;
  96. std::string const& outvar = args.back();
  97. std::string output;
  98. for (cc = 1; cc < args.size() - 1; cc++) {
  99. int ch = atoi(args[cc].c_str());
  100. if (ch > 0 && ch < 256) {
  101. output += static_cast<char>(ch);
  102. } else {
  103. std::string error =
  104. cmStrCat("Character with code ", args[cc], " does not exist.");
  105. status.SetError(error);
  106. return false;
  107. }
  108. }
  109. // Store the output in the provided variable.
  110. status.GetMakefile().AddDefinition(outvar, output);
  111. return true;
  112. }
  113. bool HandleHexCommand(std::vector<std::string> const& args,
  114. cmExecutionStatus& status)
  115. {
  116. if (args.size() != 3) {
  117. status.SetError("Incorrect number of arguments");
  118. return false;
  119. }
  120. auto const& instr = args[1];
  121. auto const& outvar = args[2];
  122. std::string output(instr.size() * 2, ' ');
  123. std::string::size_type hexIndex = 0;
  124. for (auto const& c : instr) {
  125. snprintf(&output[hexIndex], 3, "%.2x", c & 0xFFu);
  126. hexIndex += 2;
  127. }
  128. status.GetMakefile().AddDefinition(outvar, output);
  129. return true;
  130. }
  131. bool HandleConfigureCommand(std::vector<std::string> const& args,
  132. cmExecutionStatus& status)
  133. {
  134. if (args.size() < 2) {
  135. status.SetError("No input string specified.");
  136. return false;
  137. }
  138. if (args.size() < 3) {
  139. status.SetError("No output variable specified.");
  140. return false;
  141. }
  142. // Parse options.
  143. bool escapeQuotes = false;
  144. bool atOnly = false;
  145. for (unsigned int i = 3; i < args.size(); ++i) {
  146. if (args[i] == "@ONLY") {
  147. atOnly = true;
  148. } else if (args[i] == "ESCAPE_QUOTES") {
  149. escapeQuotes = true;
  150. } else {
  151. status.SetError(cmStrCat("Unrecognized argument \"", args[i], '"'));
  152. return false;
  153. }
  154. }
  155. // Configure the string.
  156. std::string output;
  157. status.GetMakefile().ConfigureString(args[1], output, atOnly, escapeQuotes);
  158. // Store the output in the provided variable.
  159. status.GetMakefile().AddDefinition(args[2], output);
  160. return true;
  161. }
  162. bool HandleRegexCommand(std::vector<std::string> const& args,
  163. cmExecutionStatus& status)
  164. {
  165. if (args.size() < 2) {
  166. status.SetError("sub-command REGEX requires a mode to be specified.");
  167. return false;
  168. }
  169. std::string const& mode = args[1];
  170. if (mode == "MATCH") {
  171. if (args.size() < 5) {
  172. status.SetError("sub-command REGEX, mode MATCH needs "
  173. "at least 5 arguments total to command.");
  174. return false;
  175. }
  176. return RegexMatch(args, status);
  177. }
  178. if (mode == "MATCHALL") {
  179. if (args.size() < 5) {
  180. status.SetError("sub-command REGEX, mode MATCHALL needs "
  181. "at least 5 arguments total to command.");
  182. return false;
  183. }
  184. return RegexMatchAll(args, status);
  185. }
  186. if (mode == "REPLACE") {
  187. if (args.size() < 6) {
  188. status.SetError("sub-command REGEX, mode REPLACE needs "
  189. "at least 6 arguments total to command.");
  190. return false;
  191. }
  192. return RegexReplace(args, status);
  193. }
  194. std::string e = "sub-command REGEX does not recognize mode " + mode;
  195. status.SetError(e);
  196. return false;
  197. }
  198. bool RegexMatch(std::vector<std::string> const& args,
  199. cmExecutionStatus& status)
  200. {
  201. //"STRING(REGEX MATCH <regular_expression> <output variable>
  202. // <input> [<input>...])\n";
  203. std::string const& regex = args[2];
  204. std::string const& outvar = args[3];
  205. status.GetMakefile().ClearMatches();
  206. // Compile the regular expression.
  207. cmsys::RegularExpression re;
  208. if (!re.compile(regex)) {
  209. std::string e =
  210. "sub-command REGEX, mode MATCH failed to compile regex \"" + regex +
  211. "\".";
  212. status.SetError(e);
  213. return false;
  214. }
  215. // Concatenate all the last arguments together.
  216. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  217. // Scan through the input for all matches.
  218. std::string output;
  219. if (re.find(input)) {
  220. status.GetMakefile().StoreMatches(re);
  221. output = re.match();
  222. }
  223. // Store the output in the provided variable.
  224. status.GetMakefile().AddDefinition(outvar, output);
  225. return true;
  226. }
  227. bool RegexMatchAll(std::vector<std::string> const& args,
  228. cmExecutionStatus& status)
  229. {
  230. //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
  231. // [<input>...])\n";
  232. std::string const& regex = args[2];
  233. std::string const& outvar = args[3];
  234. status.GetMakefile().ClearMatches();
  235. // Compile the regular expression.
  236. cmsys::RegularExpression re;
  237. if (!re.compile(regex)) {
  238. std::string e =
  239. "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex +
  240. "\".";
  241. status.SetError(e);
  242. return false;
  243. }
  244. // Concatenate all the last arguments together.
  245. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  246. unsigned optAnchor = 0;
  247. if (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0186) !=
  248. cmPolicies::NEW) {
  249. optAnchor = cmsys::RegularExpression::BOL_AT_OFFSET;
  250. }
  251. // Scan through the input for all matches.
  252. std::string output;
  253. std::string::size_type base = 0;
  254. unsigned optNonEmpty = 0;
  255. while (re.find(input, base, optAnchor | optNonEmpty)) {
  256. status.GetMakefile().ClearMatches();
  257. status.GetMakefile().StoreMatches(re);
  258. if (!output.empty() || optNonEmpty) {
  259. output += ";";
  260. }
  261. output += re.match();
  262. base = re.end();
  263. if (re.start() == input.length()) {
  264. break;
  265. }
  266. if (re.start() == re.end()) {
  267. optNonEmpty = cmsys::RegularExpression::NONEMPTY_AT_OFFSET;
  268. } else {
  269. optNonEmpty = 0;
  270. }
  271. }
  272. // Store the output in the provided variable.
  273. status.GetMakefile().AddDefinition(outvar, output);
  274. return true;
  275. }
  276. bool RegexReplace(std::vector<std::string> const& args,
  277. cmExecutionStatus& status)
  278. {
  279. //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
  280. // <output variable> <input> [<input>...])\n"
  281. std::string const& regex = args[2];
  282. std::string const& replace = args[3];
  283. std::string const& outvar = args[4];
  284. cmStringReplaceHelper replaceHelper(regex, replace, &status.GetMakefile());
  285. if (!replaceHelper.IsReplaceExpressionValid()) {
  286. status.SetError(
  287. "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
  288. return false;
  289. }
  290. status.GetMakefile().ClearMatches();
  291. if (!replaceHelper.IsRegularExpressionValid()) {
  292. std::string e =
  293. "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex +
  294. "\".";
  295. status.SetError(e);
  296. return false;
  297. }
  298. // Concatenate all the last arguments together.
  299. std::string const input =
  300. cmJoin(cmMakeRange(args).advance(5), std::string());
  301. std::string output;
  302. if (!replaceHelper.Replace(input, output)) {
  303. status.SetError(
  304. "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
  305. return false;
  306. }
  307. // Store the output in the provided variable.
  308. status.GetMakefile().AddDefinition(outvar, output);
  309. return true;
  310. }
  311. bool HandleFindCommand(std::vector<std::string> const& args,
  312. cmExecutionStatus& status)
  313. {
  314. // check if all required parameters were passed
  315. if (args.size() < 4 || args.size() > 5) {
  316. status.SetError("sub-command FIND requires 3 or 4 parameters.");
  317. return false;
  318. }
  319. // check if the reverse flag was set or not
  320. bool reverseMode = false;
  321. if (args.size() == 5 && args[4] == "REVERSE") {
  322. reverseMode = true;
  323. }
  324. // if we have 5 arguments the last one must be REVERSE
  325. if (args.size() == 5 && args[4] != "REVERSE") {
  326. status.SetError("sub-command FIND: unknown last parameter");
  327. return false;
  328. }
  329. // local parameter names.
  330. std::string const& sstring = args[1];
  331. std::string const& schar = args[2];
  332. std::string const& outvar = args[3];
  333. // ensure that the user cannot accidentally specify REVERSE as a variable
  334. if (outvar == "REVERSE") {
  335. status.SetError("sub-command FIND does not allow one to select REVERSE as "
  336. "the output variable. "
  337. "Maybe you missed the actual output variable?");
  338. return false;
  339. }
  340. // try to find the character and return its position
  341. size_t pos;
  342. if (!reverseMode) {
  343. pos = sstring.find(schar);
  344. } else {
  345. pos = sstring.rfind(schar);
  346. }
  347. if (std::string::npos != pos) {
  348. status.GetMakefile().AddDefinition(outvar, std::to_string(pos));
  349. return true;
  350. }
  351. // the character was not found, but this is not really an error
  352. status.GetMakefile().AddDefinition(outvar, "-1");
  353. return true;
  354. }
  355. bool HandleCompareCommand(std::vector<std::string> const& args,
  356. cmExecutionStatus& status)
  357. {
  358. if (args.size() < 2) {
  359. status.SetError("sub-command COMPARE requires a mode to be specified.");
  360. return false;
  361. }
  362. std::string const& mode = args[1];
  363. if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
  364. (mode == "LESS_EQUAL") || (mode == "GREATER") ||
  365. (mode == "GREATER_EQUAL")) {
  366. if (args.size() < 5) {
  367. std::string e =
  368. cmStrCat("sub-command COMPARE, mode ", mode,
  369. " needs at least 5 arguments total to command.");
  370. status.SetError(e);
  371. return false;
  372. }
  373. std::string const& left = args[2];
  374. std::string const& right = args[3];
  375. std::string const& outvar = args[4];
  376. bool result;
  377. if (mode == "LESS") {
  378. result = (left < right);
  379. } else if (mode == "LESS_EQUAL") {
  380. result = (left <= right);
  381. } else if (mode == "GREATER") {
  382. result = (left > right);
  383. } else if (mode == "GREATER_EQUAL") {
  384. result = (left >= right);
  385. } else if (mode == "EQUAL") {
  386. result = (left == right);
  387. } else // if(mode == "NOTEQUAL")
  388. {
  389. result = !(left == right);
  390. }
  391. if (result) {
  392. status.GetMakefile().AddDefinition(outvar, "1");
  393. } else {
  394. status.GetMakefile().AddDefinition(outvar, "0");
  395. }
  396. return true;
  397. }
  398. std::string e = "sub-command COMPARE does not recognize mode " + mode;
  399. status.SetError(e);
  400. return false;
  401. }
  402. bool HandleReplaceCommand(std::vector<std::string> const& args,
  403. cmExecutionStatus& status)
  404. {
  405. if (args.size() < 5) {
  406. status.SetError("sub-command REPLACE requires at least four arguments.");
  407. return false;
  408. }
  409. std::string const& matchExpression = args[1];
  410. std::string const& replaceExpression = args[2];
  411. std::string const& variableName = args[3];
  412. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  413. cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
  414. replaceExpression.c_str());
  415. status.GetMakefile().AddDefinition(variableName, input);
  416. return true;
  417. }
  418. bool HandleSubstringCommand(std::vector<std::string> const& args,
  419. cmExecutionStatus& status)
  420. {
  421. if (args.size() != 5) {
  422. status.SetError("sub-command SUBSTRING requires four arguments.");
  423. return false;
  424. }
  425. std::string const& stringValue = args[1];
  426. int begin = atoi(args[2].c_str());
  427. int end = atoi(args[3].c_str());
  428. std::string const& variableName = args[4];
  429. size_t stringLength = stringValue.size();
  430. int intStringLength = static_cast<int>(stringLength);
  431. if (begin < 0 || begin > intStringLength) {
  432. status.SetError(
  433. cmStrCat("begin index: ", begin, " is out of range 0 - ", stringLength));
  434. return false;
  435. }
  436. if (end < -1) {
  437. status.SetError(cmStrCat("end index: ", end, " should be -1 or greater"));
  438. return false;
  439. }
  440. status.GetMakefile().AddDefinition(variableName,
  441. stringValue.substr(begin, end));
  442. return true;
  443. }
  444. bool HandleLengthCommand(std::vector<std::string> const& args,
  445. cmExecutionStatus& status)
  446. {
  447. if (args.size() != 3) {
  448. status.SetError("sub-command LENGTH requires two arguments.");
  449. return false;
  450. }
  451. std::string const& stringValue = args[1];
  452. std::string const& variableName = args[2];
  453. size_t length = stringValue.size();
  454. char buffer[1024];
  455. snprintf(buffer, sizeof(buffer), "%d", static_cast<int>(length));
  456. status.GetMakefile().AddDefinition(variableName, buffer);
  457. return true;
  458. }
  459. bool HandleAppendCommand(std::vector<std::string> const& args,
  460. cmExecutionStatus& status)
  461. {
  462. if (args.size() < 2) {
  463. status.SetError("sub-command APPEND requires at least one argument.");
  464. return false;
  465. }
  466. // Skip if nothing to append.
  467. if (args.size() < 3) {
  468. return true;
  469. }
  470. auto const& variableName = args[1];
  471. cm::string_view oldView{ status.GetMakefile().GetSafeDefinition(
  472. variableName) };
  473. auto const newValue = cmJoin(cmMakeRange(args).advance(2), {}, oldView);
  474. status.GetMakefile().AddDefinition(variableName, newValue);
  475. return true;
  476. }
  477. bool HandlePrependCommand(std::vector<std::string> const& args,
  478. cmExecutionStatus& status)
  479. {
  480. if (args.size() < 2) {
  481. status.SetError("sub-command PREPEND requires at least one argument.");
  482. return false;
  483. }
  484. // Skip if nothing to prepend.
  485. if (args.size() < 3) {
  486. return true;
  487. }
  488. std::string const& variable = args[1];
  489. std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
  490. cmValue oldValue = status.GetMakefile().GetDefinition(variable);
  491. if (oldValue) {
  492. value += *oldValue;
  493. }
  494. status.GetMakefile().AddDefinition(variable, value);
  495. return true;
  496. }
  497. bool HandleConcatCommand(std::vector<std::string> const& args,
  498. cmExecutionStatus& status)
  499. {
  500. if (args.size() < 2) {
  501. status.SetError("sub-command CONCAT requires at least one argument.");
  502. return false;
  503. }
  504. return joinImpl(args, std::string(), 1, status.GetMakefile());
  505. }
  506. bool HandleJoinCommand(std::vector<std::string> const& args,
  507. cmExecutionStatus& status)
  508. {
  509. if (args.size() < 3) {
  510. status.SetError("sub-command JOIN requires at least two arguments.");
  511. return false;
  512. }
  513. return joinImpl(args, args[1], 2, status.GetMakefile());
  514. }
  515. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  516. size_t const varIdx, cmMakefile& makefile)
  517. {
  518. std::string const& variableName = args[varIdx];
  519. // NOTE Items to concat/join placed right after the variable for
  520. // both `CONCAT` and `JOIN` sub-commands.
  521. std::string value = cmJoin(cmMakeRange(args).advance(varIdx + 1), glue);
  522. makefile.AddDefinition(variableName, value);
  523. return true;
  524. }
  525. bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args,
  526. cmExecutionStatus& status)
  527. {
  528. if (args.size() != 3) {
  529. status.SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
  530. return false;
  531. }
  532. std::string const& input = args[1];
  533. std::string const& variableName = args[2];
  534. status.GetMakefile().AddDefinition(variableName,
  535. cmSystemTools::MakeCidentifier(input));
  536. return true;
  537. }
  538. bool HandleGenexStripCommand(std::vector<std::string> const& args,
  539. cmExecutionStatus& status)
  540. {
  541. if (args.size() != 3) {
  542. status.SetError("sub-command GENEX_STRIP requires two arguments.");
  543. return false;
  544. }
  545. std::string const& input = args[1];
  546. std::string result = cmGeneratorExpression::Preprocess(
  547. input, cmGeneratorExpression::StripAllGeneratorExpressions);
  548. std::string const& variableName = args[2];
  549. status.GetMakefile().AddDefinition(variableName, result);
  550. return true;
  551. }
  552. bool HandleStripCommand(std::vector<std::string> const& args,
  553. cmExecutionStatus& status)
  554. {
  555. if (args.size() != 3) {
  556. status.SetError("sub-command STRIP requires two arguments.");
  557. return false;
  558. }
  559. std::string const& stringValue = args[1];
  560. std::string const& variableName = args[2];
  561. size_t inStringLength = stringValue.size();
  562. size_t startPos = inStringLength + 1;
  563. size_t endPos = 0;
  564. char const* ptr = stringValue.c_str();
  565. size_t cc;
  566. for (cc = 0; cc < inStringLength; ++cc) {
  567. if (!cmIsSpace(*ptr)) {
  568. if (startPos > inStringLength) {
  569. startPos = cc;
  570. }
  571. endPos = cc;
  572. }
  573. ++ptr;
  574. }
  575. size_t outLength = 0;
  576. // if the input string didn't contain any non-space characters, return
  577. // an empty string
  578. if (startPos > inStringLength) {
  579. outLength = 0;
  580. startPos = 0;
  581. } else {
  582. outLength = endPos - startPos + 1;
  583. }
  584. status.GetMakefile().AddDefinition(variableName,
  585. stringValue.substr(startPos, outLength));
  586. return true;
  587. }
  588. bool HandleRepeatCommand(std::vector<std::string> const& args,
  589. cmExecutionStatus& status)
  590. {
  591. cmMakefile& makefile = status.GetMakefile();
  592. // `string(REPEAT "<str>" <times> OUTPUT_VARIABLE)`
  593. enum ArgPos : std::size_t
  594. {
  595. SUB_COMMAND,
  596. VALUE,
  597. TIMES,
  598. OUTPUT_VARIABLE,
  599. TOTAL_ARGS
  600. };
  601. if (args.size() != ArgPos::TOTAL_ARGS) {
  602. makefile.IssueMessage(MessageType::FATAL_ERROR,
  603. "sub-command REPEAT requires three arguments.");
  604. return true;
  605. }
  606. unsigned long times;
  607. if (!cmStrToULong(args[ArgPos::TIMES], &times)) {
  608. makefile.IssueMessage(MessageType::FATAL_ERROR,
  609. "repeat count is not a positive number.");
  610. return true;
  611. }
  612. auto const& stringValue = args[ArgPos::VALUE];
  613. auto const& variableName = args[ArgPos::OUTPUT_VARIABLE];
  614. auto const inStringLength = stringValue.size();
  615. std::string result;
  616. switch (inStringLength) {
  617. case 0u:
  618. // Nothing to do for zero length input strings
  619. break;
  620. case 1u:
  621. // NOTE If the string to repeat consists of the only character,
  622. // use the appropriate constructor.
  623. result = std::string(times, stringValue[0]);
  624. break;
  625. default:
  626. result = std::string(inStringLength * times, char{});
  627. for (auto i = 0u; i < times; ++i) {
  628. std::copy(cm::cbegin(stringValue), cm::cend(stringValue),
  629. &result[i * inStringLength]);
  630. }
  631. break;
  632. }
  633. makefile.AddDefinition(variableName, result);
  634. return true;
  635. }
  636. bool HandleRandomCommand(std::vector<std::string> const& args,
  637. cmExecutionStatus& status)
  638. {
  639. if (args.size() < 2 || args.size() == 3 || args.size() == 5) {
  640. status.SetError("sub-command RANDOM requires at least one argument.");
  641. return false;
  642. }
  643. static bool seeded = false;
  644. bool force_seed = false;
  645. unsigned int seed = 0;
  646. int length = 5;
  647. char const cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
  648. "QWERTYUIOPASDFGHJKLZXCVBNM"
  649. "0123456789";
  650. std::string alphabet;
  651. if (args.size() > 3) {
  652. size_t i = 1;
  653. size_t stopAt = args.size() - 2;
  654. for (; i < stopAt; ++i) {
  655. if (args[i] == "LENGTH") {
  656. ++i;
  657. length = atoi(args[i].c_str());
  658. } else if (args[i] == "ALPHABET") {
  659. ++i;
  660. alphabet = args[i];
  661. } else if (args[i] == "RANDOM_SEED") {
  662. ++i;
  663. seed = static_cast<unsigned int>(atoi(args[i].c_str()));
  664. force_seed = true;
  665. }
  666. }
  667. }
  668. if (alphabet.empty()) {
  669. alphabet = cmStringCommandDefaultAlphabet;
  670. }
  671. double sizeofAlphabet = static_cast<double>(alphabet.size());
  672. if (sizeofAlphabet < 1) {
  673. status.SetError("sub-command RANDOM invoked with bad alphabet.");
  674. return false;
  675. }
  676. if (length < 1) {
  677. status.SetError("sub-command RANDOM invoked with bad length.");
  678. return false;
  679. }
  680. std::string const& variableName = args.back();
  681. std::vector<char> result;
  682. if (!seeded || force_seed) {
  683. seeded = true;
  684. srand(force_seed ? seed : cmSystemTools::RandomSeed());
  685. }
  686. char const* alphaPtr = alphabet.c_str();
  687. for (int cc = 0; cc < length; cc++) {
  688. int idx = static_cast<int>(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
  689. result.push_back(*(alphaPtr + idx));
  690. }
  691. result.push_back(0);
  692. status.GetMakefile().AddDefinition(variableName, result.data());
  693. return true;
  694. }
  695. bool HandleTimestampCommand(std::vector<std::string> const& args,
  696. cmExecutionStatus& status)
  697. {
  698. if (args.size() < 2) {
  699. status.SetError("sub-command TIMESTAMP requires at least one argument.");
  700. return false;
  701. }
  702. if (args.size() > 4) {
  703. status.SetError("sub-command TIMESTAMP takes at most three arguments.");
  704. return false;
  705. }
  706. unsigned int argsIndex = 1;
  707. std::string const& outputVariable = args[argsIndex++];
  708. std::string formatString;
  709. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  710. formatString = args[argsIndex++];
  711. }
  712. bool utcFlag = false;
  713. if (args.size() > argsIndex) {
  714. if (args[argsIndex] == "UTC") {
  715. utcFlag = true;
  716. } else {
  717. std::string e = " TIMESTAMP sub-command does not recognize option " +
  718. args[argsIndex] + ".";
  719. status.SetError(e);
  720. return false;
  721. }
  722. }
  723. cmTimestamp timestamp;
  724. std::string result = timestamp.CurrentTime(formatString, utcFlag);
  725. status.GetMakefile().AddDefinition(outputVariable, result);
  726. return true;
  727. }
  728. bool HandleUuidCommand(std::vector<std::string> const& args,
  729. cmExecutionStatus& status)
  730. {
  731. #if !defined(CMAKE_BOOTSTRAP)
  732. unsigned int argsIndex = 1;
  733. if (args.size() < 2) {
  734. status.SetError("UUID sub-command requires an output variable.");
  735. return false;
  736. }
  737. std::string const& outputVariable = args[argsIndex++];
  738. std::string uuidNamespaceString;
  739. std::string uuidName;
  740. std::string uuidType;
  741. bool uuidUpperCase = false;
  742. while (args.size() > argsIndex) {
  743. if (args[argsIndex] == "NAMESPACE") {
  744. ++argsIndex;
  745. if (argsIndex >= args.size()) {
  746. status.SetError("UUID sub-command, NAMESPACE requires a value.");
  747. return false;
  748. }
  749. uuidNamespaceString = args[argsIndex++];
  750. } else if (args[argsIndex] == "NAME") {
  751. ++argsIndex;
  752. if (argsIndex >= args.size()) {
  753. status.SetError("UUID sub-command, NAME requires a value.");
  754. return false;
  755. }
  756. uuidName = args[argsIndex++];
  757. } else if (args[argsIndex] == "TYPE") {
  758. ++argsIndex;
  759. if (argsIndex >= args.size()) {
  760. status.SetError("UUID sub-command, TYPE requires a value.");
  761. return false;
  762. }
  763. uuidType = args[argsIndex++];
  764. } else if (args[argsIndex] == "UPPER") {
  765. ++argsIndex;
  766. uuidUpperCase = true;
  767. } else {
  768. std::string e =
  769. "UUID sub-command does not recognize option " + args[argsIndex] + ".";
  770. status.SetError(e);
  771. return false;
  772. }
  773. }
  774. std::string uuid;
  775. cmUuid uuidGenerator;
  776. std::vector<unsigned char> uuidNamespace;
  777. if (!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace)) {
  778. status.SetError("UUID sub-command, malformed NAMESPACE UUID.");
  779. return false;
  780. }
  781. if (uuidType == "MD5") {
  782. uuid = uuidGenerator.FromMd5(uuidNamespace, uuidName);
  783. } else if (uuidType == "SHA1") {
  784. uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName);
  785. } else {
  786. std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'.";
  787. status.SetError(e);
  788. return false;
  789. }
  790. if (uuid.empty()) {
  791. status.SetError("UUID sub-command, generation failed.");
  792. return false;
  793. }
  794. if (uuidUpperCase) {
  795. uuid = cmSystemTools::UpperCase(uuid);
  796. }
  797. status.GetMakefile().AddDefinition(outputVariable, uuid);
  798. return true;
  799. #else
  800. status.SetError(cmStrCat(args[0], " not available during bootstrap"));
  801. return false;
  802. #endif
  803. }
  804. #if !defined(CMAKE_BOOTSTRAP)
  805. // Helpers for string(JSON ...)
  806. struct Args : cmRange<typename std::vector<std::string>::const_iterator>
  807. {
  808. using cmRange<typename std::vector<std::string>::const_iterator>::cmRange;
  809. auto PopFront(cm::string_view error) -> std::string const&;
  810. auto PopBack(cm::string_view error) -> std::string const&;
  811. };
  812. class json_error : public std::runtime_error
  813. {
  814. public:
  815. json_error(std::string const& message,
  816. cm::optional<Args> errorPath = cm::nullopt)
  817. : std::runtime_error(message)
  818. , ErrorPath{
  819. std::move(errorPath) // NOLINT(performance-move-const-arg)
  820. }
  821. {
  822. }
  823. cm::optional<Args> ErrorPath;
  824. };
  825. std::string const& Args::PopFront(cm::string_view error)
  826. {
  827. if (this->empty()) {
  828. throw json_error(std::string(error));
  829. }
  830. std::string const& res = *this->begin();
  831. this->advance(1);
  832. return res;
  833. }
  834. std::string const& Args::PopBack(cm::string_view error)
  835. {
  836. if (this->empty()) {
  837. throw json_error(std::string(error));
  838. }
  839. std::string const& res = *(this->end() - 1);
  840. this->retreat(1);
  841. return res;
  842. }
  843. cm::string_view JsonTypeToString(Json::ValueType type)
  844. {
  845. switch (type) {
  846. case Json::ValueType::nullValue:
  847. return "NULL"_s;
  848. case Json::ValueType::intValue:
  849. case Json::ValueType::uintValue:
  850. case Json::ValueType::realValue:
  851. return "NUMBER"_s;
  852. case Json::ValueType::stringValue:
  853. return "STRING"_s;
  854. case Json::ValueType::booleanValue:
  855. return "BOOLEAN"_s;
  856. case Json::ValueType::arrayValue:
  857. return "ARRAY"_s;
  858. case Json::ValueType::objectValue:
  859. return "OBJECT"_s;
  860. }
  861. throw json_error("invalid JSON type found");
  862. }
  863. int ParseIndex(
  864. std::string const& str, cm::optional<Args> const& progress = cm::nullopt,
  865. Json::ArrayIndex max = std::numeric_limits<Json::ArrayIndex>::max())
  866. {
  867. unsigned long lindex;
  868. if (!cmStrToULong(str, &lindex)) {
  869. throw json_error(cmStrCat("expected an array index, got: '"_s, str, "'"_s),
  870. progress);
  871. }
  872. Json::ArrayIndex index = static_cast<Json::ArrayIndex>(lindex);
  873. if (index >= max) {
  874. cmAlphaNum sizeStr{ max };
  875. throw json_error(cmStrCat("expected an index less than "_s, sizeStr.View(),
  876. " got '"_s, str, "'"_s),
  877. progress);
  878. }
  879. return index;
  880. }
  881. Json::Value& ResolvePath(Json::Value& json, Args path)
  882. {
  883. Json::Value* search = &json;
  884. for (auto curr = path.begin(); curr != path.end(); ++curr) {
  885. std::string const& field = *curr;
  886. Args progress{ path.begin(), curr + 1 };
  887. if (search->isArray()) {
  888. auto index = ParseIndex(field, progress, search->size());
  889. search = &(*search)[index];
  890. } else if (search->isObject()) {
  891. if (!search->isMember(field)) {
  892. auto const progressStr = cmJoin(progress, " "_s);
  893. throw json_error(cmStrCat("member '"_s, progressStr, "' not found"_s),
  894. progress);
  895. }
  896. search = &(*search)[field];
  897. } else {
  898. auto const progressStr = cmJoin(progress, " "_s);
  899. throw json_error(
  900. cmStrCat("invalid path '"_s, progressStr,
  901. "', need element of OBJECT or ARRAY type to lookup '"_s,
  902. field, "' got "_s, JsonTypeToString(search->type())),
  903. progress);
  904. }
  905. }
  906. return *search;
  907. }
  908. Json::Value ReadJson(std::string const& jsonstr)
  909. {
  910. Json::CharReaderBuilder builder;
  911. builder["collectComments"] = false;
  912. auto jsonReader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
  913. Json::Value json;
  914. std::string error;
  915. if (!jsonReader->parse(jsonstr.data(), jsonstr.data() + jsonstr.size(),
  916. &json, &error)) {
  917. throw json_error(cmStrCat("failed parsing json string: "_s, error));
  918. }
  919. return json;
  920. }
  921. std::string WriteJson(Json::Value const& value)
  922. {
  923. Json::StreamWriterBuilder writer;
  924. writer["indentation"] = " ";
  925. writer["commentStyle"] = "None";
  926. return Json::writeString(writer, value);
  927. }
  928. #endif
  929. bool HandleJSONCommand(std::vector<std::string> const& arguments,
  930. cmExecutionStatus& status)
  931. {
  932. #if !defined(CMAKE_BOOTSTRAP)
  933. auto& makefile = status.GetMakefile();
  934. Args args{ arguments.begin() + 1, arguments.end() };
  935. std::string const* errorVariable = nullptr;
  936. std::string const* outputVariable = nullptr;
  937. bool success = true;
  938. try {
  939. outputVariable = &args.PopFront("missing out-var argument"_s);
  940. if (!args.empty() && *args.begin() == "ERROR_VARIABLE"_s) {
  941. args.PopFront("");
  942. errorVariable = &args.PopFront("missing error-var argument"_s);
  943. makefile.AddDefinition(*errorVariable, "NOTFOUND"_s);
  944. }
  945. auto const& mode = args.PopFront("missing mode argument"_s);
  946. if (mode != "GET"_s && mode != "TYPE"_s && mode != "MEMBER"_s &&
  947. mode != "LENGTH"_s && mode != "REMOVE"_s && mode != "SET"_s &&
  948. mode != "EQUAL"_s) {
  949. throw json_error(
  950. cmStrCat("got an invalid mode '"_s, mode,
  951. "', expected one of GET, TYPE, MEMBER, LENGTH, REMOVE, SET, "
  952. " EQUAL"_s));
  953. }
  954. auto const& jsonstr = args.PopFront("missing json string argument"_s);
  955. Json::Value json = ReadJson(jsonstr);
  956. if (mode == "GET"_s) {
  957. auto const& value = ResolvePath(json, args);
  958. if (value.isObject() || value.isArray()) {
  959. makefile.AddDefinition(*outputVariable, WriteJson(value));
  960. } else if (value.isBool()) {
  961. makefile.AddDefinitionBool(*outputVariable, value.asBool());
  962. } else {
  963. makefile.AddDefinition(*outputVariable, value.asString());
  964. }
  965. } else if (mode == "TYPE"_s) {
  966. auto const& value = ResolvePath(json, args);
  967. makefile.AddDefinition(*outputVariable, JsonTypeToString(value.type()));
  968. } else if (mode == "MEMBER"_s) {
  969. auto const& indexStr = args.PopBack("missing member index"_s);
  970. auto const& value = ResolvePath(json, args);
  971. if (!value.isObject()) {
  972. throw json_error(
  973. cmStrCat("MEMBER needs to be called with an element of "
  974. "type OBJECT, got "_s,
  975. JsonTypeToString(value.type())),
  976. args);
  977. }
  978. auto const index = ParseIndex(
  979. indexStr, Args{ args.begin(), args.end() + 1 }, value.size());
  980. auto const memIt = std::next(value.begin(), index);
  981. makefile.AddDefinition(*outputVariable, memIt.name());
  982. } else if (mode == "LENGTH"_s) {
  983. auto const& value = ResolvePath(json, args);
  984. if (!value.isArray() && !value.isObject()) {
  985. throw json_error(cmStrCat("LENGTH needs to be called with an "
  986. "element of type ARRAY or OBJECT, got "_s,
  987. JsonTypeToString(value.type())),
  988. args);
  989. }
  990. cmAlphaNum sizeStr{ value.size() };
  991. makefile.AddDefinition(*outputVariable, sizeStr.View());
  992. } else if (mode == "REMOVE"_s) {
  993. auto const& toRemove =
  994. args.PopBack("missing member or index to remove"_s);
  995. auto& value = ResolvePath(json, args);
  996. if (value.isArray()) {
  997. auto const index = ParseIndex(
  998. toRemove, Args{ args.begin(), args.end() + 1 }, value.size());
  999. Json::Value removed;
  1000. value.removeIndex(index, &removed);
  1001. } else if (value.isObject()) {
  1002. Json::Value removed;
  1003. value.removeMember(toRemove, &removed);
  1004. } else {
  1005. throw json_error(cmStrCat("REMOVE needs to be called with an "
  1006. "element of type ARRAY or OBJECT, got "_s,
  1007. JsonTypeToString(value.type())),
  1008. args);
  1009. }
  1010. makefile.AddDefinition(*outputVariable, WriteJson(json));
  1011. } else if (mode == "SET"_s) {
  1012. auto const& newValueStr = args.PopBack("missing new value remove"_s);
  1013. auto const& toAdd = args.PopBack("missing member name to add"_s);
  1014. auto& value = ResolvePath(json, args);
  1015. Json::Value newValue = ReadJson(newValueStr);
  1016. if (value.isObject()) {
  1017. value[toAdd] = newValue;
  1018. } else if (value.isArray()) {
  1019. auto const index =
  1020. ParseIndex(toAdd, Args{ args.begin(), args.end() + 1 });
  1021. if (value.isValidIndex(index)) {
  1022. value[static_cast<int>(index)] = newValue;
  1023. } else {
  1024. value.append(newValue);
  1025. }
  1026. } else {
  1027. throw json_error(cmStrCat("SET needs to be called with an "
  1028. "element of type OBJECT or ARRAY, got "_s,
  1029. JsonTypeToString(value.type())));
  1030. }
  1031. makefile.AddDefinition(*outputVariable, WriteJson(json));
  1032. } else if (mode == "EQUAL"_s) {
  1033. auto const& jsonstr2 =
  1034. args.PopFront("missing second json string argument"_s);
  1035. Json::Value json2 = ReadJson(jsonstr2);
  1036. makefile.AddDefinitionBool(*outputVariable, json == json2);
  1037. }
  1038. } catch (json_error const& e) {
  1039. if (outputVariable && e.ErrorPath) {
  1040. auto const errorPath = cmJoin(*e.ErrorPath, "-");
  1041. makefile.AddDefinition(*outputVariable,
  1042. cmStrCat(errorPath, "-NOTFOUND"_s));
  1043. } else if (outputVariable) {
  1044. makefile.AddDefinition(*outputVariable, "NOTFOUND"_s);
  1045. }
  1046. if (errorVariable) {
  1047. makefile.AddDefinition(*errorVariable, e.what());
  1048. } else {
  1049. status.SetError(cmStrCat("sub-command JSON "_s, e.what(), "."_s));
  1050. success = false;
  1051. }
  1052. }
  1053. return success;
  1054. #else
  1055. status.SetError(cmStrCat(arguments[0], " not available during bootstrap"_s));
  1056. return false;
  1057. #endif
  1058. }
  1059. } // namespace
  1060. bool cmStringCommand(std::vector<std::string> const& args,
  1061. cmExecutionStatus& status)
  1062. {
  1063. if (args.empty()) {
  1064. status.SetError("must be called with at least one argument.");
  1065. return false;
  1066. }
  1067. static cmSubcommandTable const subcommand{
  1068. { "REGEX"_s, HandleRegexCommand },
  1069. { "REPLACE"_s, HandleReplaceCommand },
  1070. { "MD5"_s, HandleHashCommand },
  1071. { "SHA1"_s, HandleHashCommand },
  1072. { "SHA224"_s, HandleHashCommand },
  1073. { "SHA256"_s, HandleHashCommand },
  1074. { "SHA384"_s, HandleHashCommand },
  1075. { "SHA512"_s, HandleHashCommand },
  1076. { "SHA3_224"_s, HandleHashCommand },
  1077. { "SHA3_256"_s, HandleHashCommand },
  1078. { "SHA3_384"_s, HandleHashCommand },
  1079. { "SHA3_512"_s, HandleHashCommand },
  1080. { "TOLOWER"_s, HandleToLowerCommand },
  1081. { "TOUPPER"_s, HandleToUpperCommand },
  1082. { "COMPARE"_s, HandleCompareCommand },
  1083. { "ASCII"_s, HandleAsciiCommand },
  1084. { "HEX"_s, HandleHexCommand },
  1085. { "CONFIGURE"_s, HandleConfigureCommand },
  1086. { "LENGTH"_s, HandleLengthCommand },
  1087. { "APPEND"_s, HandleAppendCommand },
  1088. { "PREPEND"_s, HandlePrependCommand },
  1089. { "CONCAT"_s, HandleConcatCommand },
  1090. { "JOIN"_s, HandleJoinCommand },
  1091. { "SUBSTRING"_s, HandleSubstringCommand },
  1092. { "STRIP"_s, HandleStripCommand },
  1093. { "REPEAT"_s, HandleRepeatCommand },
  1094. { "RANDOM"_s, HandleRandomCommand },
  1095. { "FIND"_s, HandleFindCommand },
  1096. { "TIMESTAMP"_s, HandleTimestampCommand },
  1097. { "MAKE_C_IDENTIFIER"_s, HandleMakeCIdentifierCommand },
  1098. { "GENEX_STRIP"_s, HandleGenexStripCommand },
  1099. { "UUID"_s, HandleUuidCommand },
  1100. { "JSON"_s, HandleJSONCommand },
  1101. };
  1102. return subcommand(args[0], args, status);
  1103. }