cmStringCommand.cxx 37 KB

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