cmStringCommand.cxx 37 KB

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