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