1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "qmakeevaluator.h"
5
6#include "qmakeevaluator_p.h"
7#include "qmakeglobals.h"
8#include "qmakeparser.h"
9#include "qmakevfs.h"
10#include "ioutils.h"
11
12#include <qbytearray.h>
13#include <qdir.h>
14#include <qfile.h>
15#include <qfileinfo.h>
16#include <qjsonarray.h>
17#include <qjsondocument.h>
18#include <qjsonobject.h>
19#include <qlist.h>
20#include <qregularexpression.h>
21#include <qset.h>
22#include <qstringlist.h>
23#include <qtextstream.h>
24
25#ifdef PROEVALUATOR_THREAD_SAFE
26# include <qthreadpool.h>
27#endif
28#include <qversionnumber.h>
29#ifdef Q_OS_WIN
30# include <registry_p.h>
31#endif
32
33#include <algorithm>
34
35#ifdef Q_OS_UNIX
36#include <time.h>
37#include <errno.h>
38#include <unistd.h>
39#include <signal.h>
40#include <sys/wait.h>
41#include <sys/stat.h>
42#include <sys/utsname.h>
43#else
44#include <qt_windows.h>
45#endif
46#include <stdio.h>
47#include <stdlib.h>
48
49#ifdef Q_OS_WIN32
50#define QT_POPEN _popen
51#define QT_POPEN_READ "rb"
52#define QT_PCLOSE _pclose
53#else
54#define QT_POPEN popen
55#define QT_POPEN_READ "r"
56#define QT_PCLOSE pclose
57#endif
58
59using namespace QMakeInternal;
60
61QT_BEGIN_NAMESPACE
62
63#define fL1S(s) QString::fromLatin1(s)
64
65enum ExpandFunc {
66 E_INVALID = 0, E_MEMBER, E_STR_MEMBER, E_FIRST, E_TAKE_FIRST, E_LAST, E_TAKE_LAST,
67 E_SIZE, E_STR_SIZE, E_CAT, E_FROMFILE, E_EVAL, E_LIST, E_SPRINTF, E_FORMAT_NUMBER,
68 E_NUM_ADD, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
69 E_FIND, E_SYSTEM, E_UNIQUE, E_SORTED, E_REVERSE, E_QUOTE, E_ESCAPE_EXPAND,
70 E_UPPER, E_LOWER, E_TITLE, E_FILES, E_PROMPT, E_RE_ESCAPE, E_VAL_ESCAPE,
71 E_REPLACE, E_SORT_DEPENDS, E_RESOLVE_DEPENDS, E_ENUMERATE_VARS,
72 E_SHADOWED, E_ABSOLUTE_PATH, E_RELATIVE_PATH, E_CLEAN_PATH,
73 E_SYSTEM_PATH, E_SHELL_PATH, E_SYSTEM_QUOTE, E_SHELL_QUOTE, E_GETENV, E_READ_REGISTRY
74};
75
76enum TestFunc {
77 T_INVALID = 0, T_REQUIRES, T_GREATERTHAN, T_LESSTHAN, T_EQUALS,
78 T_VERSION_AT_LEAST, T_VERSION_AT_MOST,
79 T_EXISTS, T_EXPORT, T_CLEAR, T_UNSET, T_EVAL, T_CONFIG, T_SYSTEM,
80 T_DEFINED, T_DISCARD_FROM, T_CONTAINS, T_INFILE,
81 T_COUNT, T_ISEMPTY, T_PARSE_JSON, T_INCLUDE, T_LOAD, T_DEBUG, T_LOG, T_MESSAGE, T_WARNING, T_ERROR, T_IF,
82 T_MKPATH, T_WRITE_FILE, T_TOUCH, T_CACHE, T_RELOAD_PROPERTIES
83};
84
85QMakeBuiltin::QMakeBuiltin(const QMakeBuiltinInit &d)
86 : index(d.func), minArgs(qMax(a: 0, b: d.min_args)), maxArgs(d.max_args)
87{
88 static const char * const nstr[6] = { "no", "one", "two", "three", "four", "five" };
89 // For legacy reasons, there is actually no such thing as "no arguments"
90 // - there is only "empty first argument", which needs to be mapped back.
91 // -1 means "one, which may be empty", which is effectively zero, except
92 // for the error message if there are too many arguments.
93 int dmin = qAbs(t: d.min_args);
94 int dmax = d.max_args;
95 if (dmax == QMakeBuiltinInit::VarArgs) {
96 Q_ASSERT_X(dmin < 2, "init", d.name);
97 if (dmin == 1) {
98 Q_ASSERT_X(d.args != nullptr, "init", d.name);
99 usage = fL1S("%1(%2) requires at least one argument.")
100 .arg(fL1S(d.name), fL1S(d.args));
101 }
102 return;
103 }
104 int arange = dmax - dmin;
105 Q_ASSERT_X(arange >= 0, "init", d.name);
106 Q_ASSERT_X(d.args != nullptr, "init", d.name);
107 usage = arange > 1
108 ? fL1S("%1(%2) requires %3 to %4 arguments.")
109 .arg(fL1S(d.name), fL1S(d.args), fL1S(nstr[dmin]), fL1S(nstr[dmax]))
110 : arange > 0
111 ? fL1S("%1(%2) requires %3 or %4 arguments.")
112 .arg(fL1S(d.name), fL1S(d.args), fL1S(nstr[dmin]), fL1S(nstr[dmax]))
113 : dmax != 1
114 ? fL1S("%1(%2) requires %3 arguments.")
115 .arg(fL1S(d.name), fL1S(d.args), fL1S(nstr[dmax]))
116 : fL1S("%1(%2) requires one argument.")
117 .arg(fL1S(d.name), fL1S(d.args));
118}
119
120void QMakeEvaluator::initFunctionStatics()
121{
122 static const QMakeBuiltinInit expandInits[] = {
123 { .name: "member", .func: E_MEMBER, .min_args: 1, .max_args: 3, .args: "var, [start, [end]]" },
124 { .name: "str_member", .func: E_STR_MEMBER, .min_args: -1, .max_args: 3, .args: "str, [start, [end]]" },
125 { .name: "first", .func: E_FIRST, .min_args: 1, .max_args: 1, .args: "var" },
126 { .name: "take_first", .func: E_TAKE_FIRST, .min_args: 1, .max_args: 1, .args: "var" },
127 { .name: "last", .func: E_LAST, .min_args: 1, .max_args: 1, .args: "var" },
128 { .name: "take_last", .func: E_TAKE_LAST, .min_args: 1, .max_args: 1, .args: "var" },
129 { .name: "size", .func: E_SIZE, .min_args: 1, .max_args: 1, .args: "var" },
130 { .name: "str_size", .func: E_STR_SIZE, .min_args: -1, .max_args: 1, .args: "str" },
131 { .name: "cat", .func: E_CAT, .min_args: 1, .max_args: 2, .args: "file, [mode=true|blob|lines]" },
132 { .name: "fromfile", .func: E_FROMFILE, .min_args: 2, .max_args: 2, .args: "file, var" },
133 { .name: "eval", .func: E_EVAL, .min_args: 1, .max_args: 1, .args: "var" },
134 { .name: "list", .func: E_LIST, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
135 { .name: "sprintf", .func: E_SPRINTF, .min_args: 1, .max_args: QMakeBuiltinInit::VarArgs, .args: "format, ..." },
136 { .name: "format_number", .func: E_FORMAT_NUMBER, .min_args: 1, .max_args: 2, .args: "number, [options...]" },
137 { .name: "num_add", .func: E_NUM_ADD, .min_args: 1, .max_args: QMakeBuiltinInit::VarArgs, .args: "num, ..." },
138 { .name: "join", .func: E_JOIN, .min_args: 1, .max_args: 4, .args: "var, [glue, [before, [after]]]" },
139 { .name: "split", .func: E_SPLIT, .min_args: 1, .max_args: 2, .args: "var, sep" },
140 { .name: "basename", .func: E_BASENAME, .min_args: 1, .max_args: 1, .args: "var" },
141 { .name: "dirname", .func: E_DIRNAME, .min_args: 1, .max_args: 1, .args: "var" },
142 { .name: "section", .func: E_SECTION, .min_args: 3, .max_args: 4, .args: "var, sep, begin, [end]" },
143 { .name: "find", .func: E_FIND, .min_args: 2, .max_args: 2, .args: "var, str" },
144 { .name: "system", .func: E_SYSTEM, .min_args: 1, .max_args: 3, .args: "command, [mode], [stsvar]" },
145 { .name: "unique", .func: E_UNIQUE, .min_args: 1, .max_args: 1, .args: "var" },
146 { .name: "sorted", .func: E_SORTED, .min_args: 1, .max_args: 1, .args: "var" },
147 { .name: "reverse", .func: E_REVERSE, .min_args: 1, .max_args: 1, .args: "var" },
148 { .name: "quote", .func: E_QUOTE, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
149 { .name: "escape_expand", .func: E_ESCAPE_EXPAND, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
150 { .name: "upper", .func: E_UPPER, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
151 { .name: "lower", .func: E_LOWER, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
152 { .name: "title", .func: E_TITLE, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
153 { .name: "re_escape", .func: E_RE_ESCAPE, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
154 { .name: "val_escape", .func: E_VAL_ESCAPE, .min_args: 1, .max_args: 1, .args: "var" },
155 { .name: "files", .func: E_FILES, .min_args: 1, .max_args: 2, .args: "pattern, [recursive=false]" },
156 { .name: "prompt", .func: E_PROMPT, .min_args: 1, .max_args: 2, .args: "question, [decorate=true]" },
157 { .name: "replace", .func: E_REPLACE, .min_args: 3, .max_args: 3, .args: "var, before, after" },
158 { .name: "sort_depends", .func: E_SORT_DEPENDS, .min_args: 1, .max_args: 4, .args: "var, [prefix, [suffixes, [prio-suffix]]]" },
159 { .name: "resolve_depends", .func: E_RESOLVE_DEPENDS, .min_args: 1, .max_args: 4, .args: "var, [prefix, [suffixes, [prio-suffix]]]" },
160 { .name: "enumerate_vars", .func: E_ENUMERATE_VARS, .min_args: 0, .max_args: 0, .args: "" },
161 { .name: "shadowed", .func: E_SHADOWED, .min_args: 1, .max_args: 1, .args: "path" },
162 { .name: "absolute_path", .func: E_ABSOLUTE_PATH, .min_args: -1, .max_args: 2, .args: "path, [base]" },
163 { .name: "relative_path", .func: E_RELATIVE_PATH, .min_args: -1, .max_args: 2, .args: "path, [base]" },
164 { .name: "clean_path", .func: E_CLEAN_PATH, .min_args: -1, .max_args: 1, .args: "path" },
165 { .name: "system_path", .func: E_SYSTEM_PATH, .min_args: -1, .max_args: 1, .args: "path" },
166 { .name: "shell_path", .func: E_SHELL_PATH, .min_args: -1, .max_args: 1, .args: "path" },
167 { .name: "system_quote", .func: E_SYSTEM_QUOTE, .min_args: -1, .max_args: 1, .args: "arg" },
168 { .name: "shell_quote", .func: E_SHELL_QUOTE, .min_args: -1, .max_args: 1, .args: "arg" },
169 { .name: "getenv", .func: E_GETENV, .min_args: 1, .max_args: 1, .args: "arg" },
170 { .name: "read_registry", .func: E_READ_REGISTRY, .min_args: 2, .max_args: 3, .args: "tree, key, [wow64]" },
171 };
172 statics.expands.reserve(size: (int)(sizeof(expandInits)/sizeof(expandInits[0])));
173 for (unsigned i = 0; i < sizeof(expandInits)/sizeof(expandInits[0]); ++i)
174 statics.expands.insert(key: ProKey(expandInits[i].name), value: QMakeBuiltin(expandInits[i]));
175
176 static const QMakeBuiltinInit testInits[] = {
177 { .name: "requires", .func: T_REQUIRES, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
178 { .name: "greaterThan", .func: T_GREATERTHAN, .min_args: 2, .max_args: 2, .args: "var, val" },
179 { .name: "lessThan", .func: T_LESSTHAN, .min_args: 2, .max_args: 2, .args: "var, val" },
180 { .name: "equals", .func: T_EQUALS, .min_args: 2, .max_args: 2, .args: "var, val" },
181 { .name: "isEqual", .func: T_EQUALS, .min_args: 2, .max_args: 2, .args: "var, val" },
182 { .name: "versionAtLeast", .func: T_VERSION_AT_LEAST, .min_args: 2, .max_args: 2, .args: "var, version" },
183 { .name: "versionAtMost", .func: T_VERSION_AT_MOST, .min_args: 2, .max_args: 2, .args: "var, version" },
184 { .name: "exists", .func: T_EXISTS, .min_args: 1, .max_args: 1, .args: "file" },
185 { .name: "export", .func: T_EXPORT, .min_args: 1, .max_args: 1, .args: "var" },
186 { .name: "clear", .func: T_CLEAR, .min_args: 1, .max_args: 1, .args: "var" },
187 { .name: "unset", .func: T_UNSET, .min_args: 1, .max_args: 1, .args: "var" },
188 { .name: "eval", .func: T_EVAL, .min_args: 0, .max_args: QMakeBuiltinInit::VarArgs, .args: nullptr },
189 { .name: "CONFIG", .func: T_CONFIG, .min_args: 1, .max_args: 2, .args: "config, [mutuals]" },
190 { .name: "if", .func: T_IF, .min_args: 1, .max_args: 1, .args: "condition" },
191 { .name: "isActiveConfig", .func: T_CONFIG, .min_args: 1, .max_args: 2, .args: "config, [mutuals]" },
192 { .name: "system", .func: T_SYSTEM, .min_args: 1, .max_args: 1, .args: "exec" },
193 { .name: "discard_from", .func: T_DISCARD_FROM, .min_args: 1, .max_args: 1, .args: "file" },
194 { .name: "defined", .func: T_DEFINED, .min_args: 1, .max_args: 2, .args: "object, [\"test\"|\"replace\"|\"var\"]" },
195 { .name: "contains", .func: T_CONTAINS, .min_args: 2, .max_args: 3, .args: "var, val, [mutuals]" },
196 { .name: "infile", .func: T_INFILE, .min_args: 2, .max_args: 3, .args: "file, var, [values]" },
197 { .name: "count", .func: T_COUNT, .min_args: 2, .max_args: 3, .args: "var, count, [op=operator]" },
198 { .name: "isEmpty", .func: T_ISEMPTY, .min_args: 1, .max_args: 1, .args: "var" },
199 { .name: "parseJson", .func: T_PARSE_JSON, .min_args: 2, .max_args: 2, .args: "var, into" },
200 { .name: "load", .func: T_LOAD, .min_args: 1, .max_args: 2, .args: "feature, [ignore_errors=false]" },
201 { .name: "include", .func: T_INCLUDE, .min_args: 1, .max_args: 3, .args: "file, [into, [silent]]" },
202 { .name: "debug", .func: T_DEBUG, .min_args: 2, .max_args: 2, .args: "level, message" },
203 { .name: "log", .func: T_LOG, .min_args: 1, .max_args: 1, .args: "message" },
204 { .name: "message", .func: T_MESSAGE, .min_args: 1, .max_args: 1, .args: "message" },
205 { .name: "warning", .func: T_WARNING, .min_args: 1, .max_args: 1, .args: "message" },
206 { .name: "error", .func: T_ERROR, .min_args: 0, .max_args: 1, .args: "message" },
207 { .name: "mkpath", .func: T_MKPATH, .min_args: 1, .max_args: 1, .args: "path" },
208 { .name: "write_file", .func: T_WRITE_FILE, .min_args: 1, .max_args: 3, .args: "name, [content var, [append] [exe]]" },
209 { .name: "touch", .func: T_TOUCH, .min_args: 2, .max_args: 2, .args: "file, reffile" },
210 { .name: "cache", .func: T_CACHE, .min_args: 0, .max_args: 3, .args: "[var], [set|add|sub] [transient] [super|stash], [srcvar]" },
211 { .name: "reload_properties", .func: T_RELOAD_PROPERTIES, .min_args: 0, .max_args: 0, .args: "" },
212 };
213 statics.functions.reserve(size: (int)(sizeof(testInits)/sizeof(testInits[0])));
214 for (unsigned i = 0; i < sizeof(testInits)/sizeof(testInits[0]); ++i)
215 statics.functions.insert(key: ProKey(testInits[i].name), value: QMakeBuiltin(testInits[i]));
216}
217
218static bool isTrue(const ProString &str)
219{
220 return !str.compare(sub: statics.strtrue, cs: Qt::CaseInsensitive) || str.toInt();
221}
222
223bool
224QMakeEvaluator::getMemberArgs(const ProKey &func, int srclen, const ProStringList &args,
225 int *start, int *end)
226{
227 *start = 0, *end = 0;
228 if (args.size() >= 2) {
229 bool ok = true;
230 const ProString &start_str = args.at(i: 1);
231 *start = start_str.toInt(ok: &ok);
232 if (!ok) {
233 if (args.size() == 2) {
234 int dotdot = start_str.indexOf(s: statics.strDotDot);
235 if (dotdot != -1) {
236 *start = start_str.left(len: dotdot).toInt(ok: &ok);
237 if (ok)
238 *end = start_str.mid(off: dotdot+2).toInt(ok: &ok);
239 }
240 }
241 if (!ok) {
242 ProStringRoUser u1(func, m_tmp1);
243 ProStringRoUser u2(start_str, m_tmp2);
244 evalError(fL1S("%1() argument 2 (start) '%2' invalid.").arg(args&: u1.str(), args&: u2.str()));
245 return false;
246 }
247 } else {
248 *end = *start;
249 if (args.size() == 3)
250 *end = args.at(i: 2).toInt(ok: &ok);
251 if (!ok) {
252 ProStringRoUser u1(func, m_tmp1);
253 ProStringRoUser u2(args.at(i: 2), m_tmp2);
254 evalError(fL1S("%1() argument 3 (end) '%2' invalid.").arg(args&: u1.str(), args&: u2.str()));
255 return false;
256 }
257 }
258 }
259 if (*start < 0)
260 *start += srclen;
261 if (*end < 0)
262 *end += srclen;
263 if (*start < 0 || *start >= srclen || *end < 0 || *end >= srclen)
264 return false;
265 return true;
266}
267
268QString
269QMakeEvaluator::quoteValue(const ProString &val)
270{
271 QString ret;
272 ret.reserve(asize: val.size());
273 const QChar *chars = val.constData();
274 bool quote = val.isEmpty();
275 bool escaping = false;
276 for (int i = 0, l = val.size(); i < l; i++) {
277 QChar c = chars[i];
278 ushort uc = c.unicode();
279 if (uc < 32) {
280 if (!escaping) {
281 escaping = true;
282 ret += QLatin1String("$$escape_expand(");
283 }
284 switch (uc) {
285 case '\r':
286 ret += QLatin1String("\\\\r");
287 break;
288 case '\n':
289 ret += QLatin1String("\\\\n");
290 break;
291 case '\t':
292 ret += QLatin1String("\\\\t");
293 break;
294 default:
295 ret += QString::fromLatin1(ba: "\\\\x%1").arg(a: uc, fieldWidth: 2, base: 16, fillChar: QLatin1Char('0'));
296 break;
297 }
298 } else {
299 if (escaping) {
300 escaping = false;
301 ret += QLatin1Char(')');
302 }
303 switch (uc) {
304 case '\\':
305 ret += QLatin1String("\\\\");
306 break;
307 case '"':
308 ret += QLatin1String("\\\"");
309 break;
310 case '\'':
311 ret += QLatin1String("\\'");
312 break;
313 case '$':
314 ret += QLatin1String("\\$");
315 break;
316 case '#':
317 ret += QLatin1String("$${LITERAL_HASH}");
318 break;
319 case 32:
320 quote = true;
321 Q_FALLTHROUGH();
322 default:
323 ret += c;
324 break;
325 }
326 }
327 }
328 if (escaping)
329 ret += QLatin1Char(')');
330 if (quote) {
331 ret.prepend(c: QLatin1Char('"'));
332 ret.append(c: QLatin1Char('"'));
333 }
334 return ret;
335}
336
337static void addJsonValue(const QJsonValue &value, const QString &keyPrefix, ProValueMap *map);
338
339static void insertJsonKeyValue(const QString &key, const QStringList &values, ProValueMap *map)
340{
341 map->insert(key: ProKey(key), value: ProStringList(values));
342}
343
344static void addJsonArray(const QJsonArray &array, const QString &keyPrefix, ProValueMap *map)
345{
346 QStringList keys;
347 const int size = array.count();
348 keys.reserve(asize: size);
349 for (int i = 0; i < size; ++i) {
350 const QString number = QString::number(i);
351 keys.append(t: number);
352 addJsonValue(value: array.at(i), keyPrefix: keyPrefix + number, map);
353 }
354 insertJsonKeyValue(key: keyPrefix + QLatin1String("_KEYS_"), values: keys, map);
355}
356
357static void addJsonObject(const QJsonObject &object, const QString &keyPrefix, ProValueMap *map)
358{
359 QStringList keys;
360 keys.reserve(asize: object.size());
361 for (auto it = object.begin(), end = object.end(); it != end; ++it) {
362 const QString key = it.key();
363 keys.append(t: key);
364 addJsonValue(value: it.value(), keyPrefix: keyPrefix + key, map);
365 }
366 insertJsonKeyValue(key: keyPrefix + QLatin1String("_KEYS_"), values: keys, map);
367}
368
369static void addJsonValue(const QJsonValue &value, const QString &keyPrefix, ProValueMap *map)
370{
371 switch (value.type()) {
372 case QJsonValue::Bool:
373 insertJsonKeyValue(key: keyPrefix, values: QStringList() << (value.toBool() ? QLatin1String("true") : QLatin1String("false")), map);
374 break;
375 case QJsonValue::Double:
376 insertJsonKeyValue(key: keyPrefix, values: QStringList() << QString::number(value.toDouble()), map);
377 break;
378 case QJsonValue::String:
379 insertJsonKeyValue(key: keyPrefix, values: QStringList() << value.toString(), map);
380 break;
381 case QJsonValue::Array:
382 addJsonArray(array: value.toArray(), keyPrefix: keyPrefix + QLatin1Char('.'), map);
383 break;
384 case QJsonValue::Object:
385 addJsonObject(object: value.toObject(), keyPrefix: keyPrefix + QLatin1Char('.'), map);
386 break;
387 default:
388 break;
389 }
390}
391
392struct ErrorPosition {
393 int line;
394 int column;
395};
396
397static ErrorPosition calculateErrorPosition(const QByteArray &json, int offset)
398{
399 ErrorPosition pos = { .line: 0, .column: 0 };
400 offset--; // offset is 1-based, switching to 0-based
401 for (int i = 0; i < offset; ++i) {
402 switch (json.at(i)) {
403 case '\n':
404 pos.line++;
405 pos.column = 0;
406 break;
407 case '\r':
408 break;
409 case '\t':
410 pos.column = (pos.column + 8) & ~7;
411 break;
412 default:
413 pos.column++;
414 break;
415 }
416 }
417 // Lines and columns in text editors are 1-based:
418 pos.line++;
419 pos.column++;
420 return pos;
421}
422
423QMakeEvaluator::VisitReturn QMakeEvaluator::parseJsonInto(const QByteArray &json, const QString &into, ProValueMap *value)
424{
425 QJsonParseError error;
426 QJsonDocument document = QJsonDocument::fromJson(json, error: &error);
427 if (document.isNull()) {
428 if (error.error != QJsonParseError::NoError) {
429 ErrorPosition errorPos = calculateErrorPosition(json, offset: error.offset);
430 evalError(fL1S("Error parsing JSON at %1:%2: %3")
431 .arg(a: errorPos.line).arg(a: errorPos.column).arg(a: error.errorString()));
432 }
433 return QMakeEvaluator::ReturnFalse;
434 }
435
436 QString currentKey = into + QLatin1Char('.');
437
438 // top-level item is either an array or object
439 if (document.isArray())
440 addJsonArray(array: document.array(), keyPrefix: currentKey, map: value);
441 else if (document.isObject())
442 addJsonObject(object: document.object(), keyPrefix: currentKey, map: value);
443 else
444 return QMakeEvaluator::ReturnFalse;
445
446 return QMakeEvaluator::ReturnTrue;
447}
448
449QMakeEvaluator::VisitReturn
450QMakeEvaluator::writeFile(const QString &ctx, const QString &fn, QIODevice::OpenMode mode,
451 QMakeVfs::VfsFlags flags, const QString &contents)
452{
453 int oldId = m_vfs->idForFileName(fn, flags: flags | QMakeVfs::VfsAccessedOnly);
454 int id = m_vfs->idForFileName(fn, flags: flags | QMakeVfs::VfsCreate);
455 QString errStr;
456 if (!m_vfs->writeFile(id, mode, flags, contents, errStr: &errStr)) {
457 evalError(fL1S("Cannot write %1file %2: %3")
458 .arg(args: ctx, args: QDir::toNativeSeparators(pathName: fn), args&: errStr));
459 return ReturnFalse;
460 }
461 if (oldId)
462 m_parser->discardFileFromCache(id: oldId);
463 return ReturnTrue;
464}
465
466#if QT_CONFIG(process)
467void QMakeEvaluator::runProcess(QProcess *proc, const QString &command) const
468{
469 proc->setWorkingDirectory(currentDirectory());
470# ifdef PROEVALUATOR_SETENV
471 if (!m_option->environment.isEmpty())
472 proc->setProcessEnvironment(m_option->environment);
473# endif
474# ifdef Q_OS_WIN
475 proc->setNativeArguments(QLatin1String("/v:off /s /c \"") + command + QLatin1Char('"'));
476 proc->start(m_option->getEnv(QLatin1String("COMSPEC")), QStringList());
477# else
478 proc->start(program: QLatin1String("/bin/sh"), arguments: QStringList() << QLatin1String("-c") << command);
479# endif
480 proc->waitForFinished(msecs: -1);
481}
482#endif
483
484QByteArray QMakeEvaluator::getCommandOutput(const QString &args, int *exitCode) const
485{
486 QByteArray out;
487#if QT_CONFIG(process)
488 QProcess proc;
489 runProcess(proc: &proc, command: args);
490 *exitCode = (proc.exitStatus() == QProcess::NormalExit) ? proc.exitCode() : -1;
491 QByteArray errout = proc.readAllStandardError();
492# ifdef PROEVALUATOR_FULL
493 // FIXME: Qt really should have the option to set forwarding per channel
494 fputs(s: errout.constData(), stderr);
495# else
496 if (!errout.isEmpty()) {
497 if (errout.endsWith('\n'))
498 errout.chop(1);
499 m_handler->message(
500 QMakeHandler::EvalError | (m_cumulative ? QMakeHandler::CumulativeEvalMessage : 0),
501 QString::fromLocal8Bit(errout));
502 }
503# endif
504 out = proc.readAllStandardOutput();
505# ifdef Q_OS_WIN
506 // FIXME: Qt's line end conversion on sequential files should really be fixed
507 out.replace("\r\n", "\n");
508# endif
509#else
510 if (FILE *proc = QT_POPEN(QString(QLatin1String("cd ")
511 + IoUtils::shellQuote(QDir::toNativeSeparators(currentDirectory()))
512 + QLatin1String(" && ") + args).toLocal8Bit().constData(), QT_POPEN_READ)) {
513 while (!feof(proc)) {
514 char buff[10 * 1024];
515 int read_in = int(fread(buff, 1, sizeof(buff), proc));
516 if (!read_in)
517 break;
518 out += QByteArray(buff, read_in);
519 }
520 int ec = QT_PCLOSE(proc);
521# ifdef Q_OS_WIN
522 *exitCode = ec >= 0 ? ec : -1;
523# else
524 *exitCode = WIFEXITED(ec) ? WEXITSTATUS(ec) : -1;
525# endif
526 }
527# ifdef Q_OS_WIN
528 out.replace("\r\n", "\n");
529# endif
530#endif
531 return out;
532}
533
534void QMakeEvaluator::populateDeps(
535 const ProStringList &deps, const ProString &prefix, const ProStringList &suffixes,
536 const ProString &priosfx,
537 QHash<ProKey, QSet<ProKey> > &dependencies, ProValueMap &dependees,
538 QMultiMap<int, ProString> &rootSet) const
539{
540 for (const ProString &item : deps)
541 if (!dependencies.contains(key: item.toKey())) {
542 QSet<ProKey> &dset = dependencies[item.toKey()]; // Always create entry
543 ProStringList depends;
544 for (const ProString &suffix : suffixes)
545 depends += values(variableName: ProKey(prefix + item + suffix));
546 if (depends.isEmpty()) {
547 rootSet.insert(key: first(variableName: ProKey(prefix + item + priosfx)).toInt(), value: item);
548 } else {
549 for (const ProString &dep : std::as_const(t&: depends)) {
550 dset.insert(value: dep.toKey());
551 dependees[dep.toKey()] << item;
552 }
553 populateDeps(deps: depends, prefix, suffixes, priosfx, dependencies, dependees, rootSet);
554 }
555 }
556}
557
558QString QMakeEvaluator::filePathArg0(const ProStringList &args)
559{
560 ProStringRoUser u1(args.at(i: 0), m_tmp1);
561 QString fn = resolvePath(fileName: u1.str());
562 fn.detach();
563 return fn;
564}
565
566QString QMakeEvaluator::filePathEnvArg0(const ProStringList &args)
567{
568 ProStringRoUser u1(args.at(i: 0), m_tmp1);
569 QString fn = resolvePath(fileName: m_option->expandEnvVars(str: u1.str()));
570 fn.detach();
571 return fn;
572}
573
574QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBuiltinExpand(
575 const QMakeBuiltin &adef, const ProKey &func, const ProStringList &args, ProStringList &ret)
576{
577 traceMsg(fmt: "calling built-in $$%s(%s)", dbgKey(func), dbgSepStrList(args));
578 int asz = args.size() > 1 ? args.size() : args.at(i: 0).isEmpty() ? 0 : 1;
579 if (asz < adef.minArgs || asz > adef.maxArgs) {
580 evalError(msg: adef.usage);
581 return ReturnTrue;
582 }
583
584 int func_t = adef.index;
585 switch (func_t) {
586 case E_BASENAME:
587 case E_DIRNAME:
588 case E_SECTION: {
589 bool regexp = false;
590 QString sep;
591 ProString var;
592 int beg = 0;
593 int end = -1;
594 if (func_t == E_SECTION) {
595 var = args[0];
596 sep = args.at(i: 1).toQString();
597 beg = args.at(i: 2).toInt();
598 if (args.size() == 4)
599 end = args.at(i: 3).toInt();
600 } else {
601 var = args[0];
602 regexp = true;
603 sep = QLatin1String("[\\\\/]");
604 if (func_t == E_DIRNAME)
605 end = -2;
606 else
607 beg = -1;
608 }
609 if (!var.isEmpty()) {
610 const auto strings = values(variableName: map(var));
611 if (regexp) {
612 QRegularExpression sepRx(sep, QRegularExpression::DotMatchesEverythingOption);
613 if (!sepRx.isValid()) {
614 evalError(fL1S("section(): Encountered invalid regular expression '%1'.").arg(a: sep));
615 goto allfail;
616 }
617 for (const ProString &str : strings) {
618 ProStringRwUser u1(str, m_tmp[m_toggle ^= 1]);
619 ret << u1.extract(s: u1.str().section(re: sepRx, start: beg, end));
620 }
621 } else {
622 for (const ProString &str : strings) {
623 ProStringRwUser u1(str, m_tmp1);
624 ret << u1.extract(s: u1.str().section(in_sep: sep, start: beg, end));
625 }
626 }
627 }
628 break;
629 }
630 case E_SPRINTF: {
631 ProStringRwUser u1(args.at(i: 0), m_tmp1);
632 QString tmp = u1.str();
633 for (int i = 1; i < args.size(); ++i)
634 tmp = tmp.arg(a: args.at(i).toQStringView());
635 ret << u1.extract(s: tmp);
636 break;
637 }
638 case E_FORMAT_NUMBER: {
639 int ibase = 10;
640 int obase = 10;
641 int width = 0;
642 bool zeropad = false;
643 bool leftalign = false;
644 enum { DefaultSign, PadSign, AlwaysSign } sign = DefaultSign;
645 if (args.size() >= 2) {
646 const auto opts = split_value_list(vals: args.at(i: 1).toQStringView());
647 for (const ProString &opt : opts) {
648 if (opt.startsWith(sub: QLatin1String("ibase="))) {
649 ibase = opt.mid(off: 6).toInt();
650 } else if (opt.startsWith(sub: QLatin1String("obase="))) {
651 obase = opt.mid(off: 6).toInt();
652 } else if (opt.startsWith(sub: QLatin1String("width="))) {
653 width = opt.mid(off: 6).toInt();
654 } else if (opt == QLatin1String("zeropad")) {
655 zeropad = true;
656 } else if (opt == QLatin1String("padsign")) {
657 sign = PadSign;
658 } else if (opt == QLatin1String("alwayssign")) {
659 sign = AlwaysSign;
660 } else if (opt == QLatin1String("leftalign")) {
661 leftalign = true;
662 } else {
663 evalError(fL1S("format_number(): invalid format option %1.")
664 .arg(a: opt.toQStringView()));
665 goto allfail;
666 }
667 }
668 }
669 if (args.at(i: 0).contains(c: QLatin1Char('.'))) {
670 evalError(fL1S("format_number(): floats are currently not supported."));
671 break;
672 }
673 bool ok;
674 qlonglong num = args.at(i: 0).toLongLong(ok: &ok, base: ibase);
675 if (!ok) {
676 evalError(fL1S("format_number(): malformed number %2 for base %1.")
677 .arg(a: ibase).arg(a: args.at(i: 0).toQStringView()));
678 break;
679 }
680 QString outstr;
681 if (num < 0) {
682 num = -num;
683 outstr = QLatin1Char('-');
684 } else if (sign == AlwaysSign) {
685 outstr = QLatin1Char('+');
686 } else if (sign == PadSign) {
687 outstr = QLatin1Char(' ');
688 }
689 QString numstr = QString::number(num, base: obase);
690 int space = width - outstr.size() - numstr.size();
691 if (space <= 0) {
692 outstr += numstr;
693 } else if (leftalign) {
694 outstr += numstr + QString(space, QLatin1Char(' '));
695 } else if (zeropad) {
696 outstr += QString(space, QLatin1Char('0')) + numstr;
697 } else {
698 outstr.prepend(s: QString(space, QLatin1Char(' ')));
699 outstr += numstr;
700 }
701 ret += ProString(outstr);
702 break;
703 }
704 case E_NUM_ADD: {
705 qlonglong sum = 0;
706 for (const ProString &arg : std::as_const(t: args)) {
707 if (arg.contains(c: QLatin1Char('.'))) {
708 evalError(fL1S("num_add(): floats are currently not supported."));
709 goto allfail;
710 }
711 bool ok;
712 qlonglong num = arg.toLongLong(ok: &ok);
713 if (!ok) {
714 evalError(fL1S("num_add(): malformed number %1.")
715 .arg(a: arg.toQStringView()));
716 goto allfail;
717 }
718 sum += num;
719 }
720 ret += ProString(QString::number(sum));
721 break;
722 }
723 case E_JOIN: {
724 ProString glue, before, after;
725 if (args.size() >= 2)
726 glue = args.at(i: 1);
727 if (args.size() >= 3)
728 before = args[2];
729 if (args.size() == 4)
730 after = args[3];
731 const ProStringList &var = values(variableName: map(var: args.at(i: 0)));
732 if (!var.isEmpty()) {
733 int src = currentFileId();
734 for (const ProString &v : var)
735 if (int s = v.sourceFile()) {
736 src = s;
737 break;
738 }
739 ret << ProString(before + var.join(sep: glue) + after).setSource(src);
740 }
741 break;
742 }
743 case E_SPLIT: {
744 ProStringRoUser u1(m_tmp1);
745 const QString &sep = (args.size() == 2) ? u1.set(args.at(i: 1)) : statics.field_sep;
746 const auto vars = values(variableName: map(var: args.at(i: 0)));
747 for (const ProString &var : vars) {
748 // FIXME: this is inconsistent with the "there are no empty strings" dogma.
749 const auto splits = var.toQStringView().split(sep, behavior: Qt::KeepEmptyParts);
750 for (const auto &splt : splits)
751 ret << ProString(splt).setSource(var);
752 }
753 break;
754 }
755 case E_MEMBER: {
756 const ProStringList &src = values(variableName: map(var: args.at(i: 0)));
757 int start, end;
758 if (getMemberArgs(func, srclen: src.size(), args, start: &start, end: &end)) {
759 ret.reserve(asize: qAbs(t: end - start) + 1);
760 if (start < end) {
761 for (int i = start; i <= end && src.size() >= i; i++)
762 ret += src.at(i);
763 } else {
764 for (int i = start; i >= end && src.size() >= i && i >= 0; i--)
765 ret += src.at(i);
766 }
767 }
768 break;
769 }
770 case E_STR_MEMBER: {
771 const ProString &src = args.at(i: 0);
772 int start, end;
773 if (getMemberArgs(func, srclen: src.size(), args, start: &start, end: &end)) {
774 QString res;
775 res.reserve(asize: qAbs(t: end - start) + 1);
776 if (start < end) {
777 for (int i = start; i <= end && src.size() >= i; i++)
778 res += src.at(i);
779 } else {
780 for (int i = start; i >= end && src.size() >= i && i >= 0; i--)
781 res += src.at(i);
782 }
783 ret += ProString(res);
784 }
785 break;
786 }
787 case E_FIRST:
788 case E_LAST: {
789 const ProStringList &var = values(variableName: map(var: args.at(i: 0)));
790 if (!var.isEmpty()) {
791 if (func_t == E_FIRST)
792 ret.append(t: var[0]);
793 else
794 ret.append(t: var.last());
795 }
796 break;
797 }
798 case E_TAKE_FIRST:
799 case E_TAKE_LAST: {
800 ProStringList &var = valuesRef(variableName: map(var: args.at(i: 0)));
801 if (!var.isEmpty()) {
802 if (func_t == E_TAKE_FIRST)
803 ret.append(t: var.takeFirst());
804 else
805 ret.append(t: var.takeLast());
806 }
807 break;
808 }
809 case E_SIZE:
810 ret.append(t: ProString(QString::number(values(variableName: map(var: args.at(i: 0))).size())));
811 break;
812 case E_STR_SIZE:
813 ret.append(t: ProString(QString::number(args.at(i: 0).size())));
814 break;
815 case E_CAT: {
816 bool blob = false;
817 bool lines = false;
818 bool singleLine = true;
819 if (args.size() > 1) {
820 if (!args.at(i: 1).compare(sub: QLatin1String("false"), cs: Qt::CaseInsensitive))
821 singleLine = false;
822 else if (!args.at(i: 1).compare(sub: QLatin1String("blob"), cs: Qt::CaseInsensitive))
823 blob = true;
824 else if (!args.at(i: 1).compare(sub: QLatin1String("lines"), cs: Qt::CaseInsensitive))
825 lines = true;
826 }
827 QString fn = filePathEnvArg0(args);
828 QFile qfile(fn);
829 if (qfile.open(flags: QIODevice::ReadOnly)) {
830 QTextStream stream(&qfile);
831 if (blob) {
832 ret += ProString(stream.readAll());
833 } else {
834 while (!stream.atEnd()) {
835 if (lines) {
836 ret += ProString(stream.readLine());
837 } else {
838 const QString &line = stream.readLine();
839 ret += split_value_list(vals: QStringView(line).trimmed());
840 if (!singleLine)
841 ret += ProString("\n");
842 }
843 }
844 }
845 }
846 break;
847 }
848 case E_FROMFILE: {
849 ProValueMap vars;
850 QString fn = filePathEnvArg0(args);
851 if (evaluateFileInto(fileName: fn, values: &vars, flags: LoadProOnly) == ReturnTrue)
852 ret = vars.value(key: map(var: args.at(i: 1)));
853 break;
854 }
855 case E_EVAL:
856 ret += values(variableName: map(var: args.at(i: 0)));
857 break;
858 case E_LIST: {
859 QString tmp(QString::asprintf(format: ".QMAKE_INTERNAL_TMP_variableName_%d", m_listCount++));
860 ret = ProStringList(ProString(tmp));
861 ProStringList lst;
862 for (const ProString &arg : args)
863 lst += split_value_list(vals: arg.toQStringView(), source: arg.sourceFile()); // Relies on deep copy
864 m_valuemapStack.top()[ret.at(i: 0).toKey()] = lst;
865 break; }
866 case E_FIND: {
867 QRegularExpression regx(args.at(i: 1).toQString(), QRegularExpression::DotMatchesEverythingOption);
868 if (!regx.isValid()) {
869 evalError(fL1S("find(): Encountered invalid regular expression '%1'.").arg(a: regx.pattern()));
870 goto allfail;
871 }
872 const auto vals = values(variableName: map(var: args.at(i: 0)));
873 for (const ProString &val : vals) {
874 ProStringRoUser u1(val, m_tmp[m_toggle ^= 1]);
875 if (u1.str().contains(re: regx))
876 ret += val;
877 }
878 break;
879 }
880 case E_SYSTEM: {
881 if (m_skipLevel)
882 break;
883 bool blob = false;
884 bool lines = false;
885 bool singleLine = true;
886 if (args.size() > 1) {
887 if (!args.at(i: 1).compare(sub: QLatin1String("false"), cs: Qt::CaseInsensitive))
888 singleLine = false;
889 else if (!args.at(i: 1).compare(sub: QLatin1String("blob"), cs: Qt::CaseInsensitive))
890 blob = true;
891 else if (!args.at(i: 1).compare(sub: QLatin1String("lines"), cs: Qt::CaseInsensitive))
892 lines = true;
893 }
894 int exitCode;
895 QByteArray bytes = getCommandOutput(args: args.at(i: 0).toQString(), exitCode: &exitCode);
896 if (args.size() > 2 && !args.at(i: 2).isEmpty()) {
897 m_valuemapStack.top()[args.at(i: 2).toKey()] =
898 ProStringList(ProString(QString::number(exitCode)));
899 }
900 if (lines) {
901 QTextStream stream(bytes);
902 while (!stream.atEnd())
903 ret += ProString(stream.readLine());
904 } else {
905 QString output = QString::fromLocal8Bit(ba: bytes);
906 if (blob) {
907 ret += ProString(output);
908 } else {
909 output.replace(before: QLatin1Char('\t'), after: QLatin1Char(' '));
910 if (singleLine)
911 output.replace(before: QLatin1Char('\n'), after: QLatin1Char(' '));
912 ret += split_value_list(vals: QStringView(output));
913 }
914 }
915 break;
916 }
917 case E_UNIQUE:
918 ret = values(variableName: map(var: args.at(i: 0)));
919 ret.removeDuplicates();
920 break;
921 case E_SORTED:
922 ret = values(variableName: map(var: args.at(i: 0)));
923 std::sort(first: ret.begin(), last: ret.end());
924 break;
925 case E_REVERSE: {
926 ProStringList var = values(variableName: args.at(i: 0).toKey());
927 for (int i = 0; i < var.size() / 2; i++)
928 qSwap(value1&: var[i], value2&: var[var.size() - i - 1]);
929 ret += var;
930 break;
931 }
932 case E_QUOTE:
933 ret += args;
934 break;
935 case E_ESCAPE_EXPAND:
936 for (int i = 0; i < args.size(); ++i) {
937 QString str = args.at(i).toQString();
938 QChar *i_data = str.data();
939 int i_len = str.size();
940 for (int x = 0; x < i_len; ++x) {
941 if (*(i_data+x) == QLatin1Char('\\') && x < i_len-1) {
942 if (*(i_data+x+1) == QLatin1Char('\\')) {
943 ++x;
944 } else {
945 struct {
946 char in, out;
947 } mapped_quotes[] = {
948 { .in: 'n', .out: '\n' },
949 { .in: 't', .out: '\t' },
950 { .in: 'r', .out: '\r' },
951 { .in: 0, .out: 0 }
952 };
953 for (int i = 0; mapped_quotes[i].in; ++i) {
954 if (*(i_data+x+1) == QLatin1Char(mapped_quotes[i].in)) {
955 *(i_data+x) = QLatin1Char(mapped_quotes[i].out);
956 if (x < i_len-2)
957 memmove(dest: i_data+x+1, src: i_data+x+2, n: (i_len-x-2)*sizeof(QChar));
958 --i_len;
959 break;
960 }
961 }
962 }
963 }
964 }
965 ret.append(t: ProString(QString(i_data, i_len)).setSource(args.at(i)));
966 }
967 break;
968 case E_RE_ESCAPE:
969 for (int i = 0; i < args.size(); ++i) {
970 ProStringRwUser u1(args.at(i), m_tmp1);
971 ret << u1.extract(s: QRegularExpression::escape(str: u1.str()));
972 }
973 break;
974 case E_VAL_ESCAPE: {
975 const ProStringList &vals = values(variableName: args.at(i: 0).toKey());
976 ret.reserve(asize: vals.size());
977 for (const ProString &str : vals)
978 ret += ProString(quoteValue(val: str));
979 break;
980 }
981 case E_UPPER:
982 case E_LOWER:
983 case E_TITLE:
984 for (int i = 0; i < args.size(); ++i) {
985 ProStringRwUser u1(args.at(i), m_tmp1);
986 QString rstr = u1.str();
987 if (func_t == E_UPPER) {
988 rstr = rstr.toUpper();
989 } else {
990 rstr = rstr.toLower();
991 if (func_t == E_TITLE && rstr.size() > 0)
992 rstr[0] = rstr.at(i: 0).toTitleCase();
993 }
994 ret << u1.extract(s: rstr);
995 }
996 break;
997 case E_FILES: {
998 bool recursive = false;
999 if (args.size() == 2)
1000 recursive = isTrue(str: args.at(i: 1));
1001 QStringList dirs;
1002 ProStringRoUser u1(args.at(i: 0), m_tmp1);
1003 QString r = m_option->expandEnvVars(str: u1.str())
1004 .replace(before: QLatin1Char('\\'), after: QLatin1Char('/'));
1005 QString pfx;
1006 if (IoUtils::isRelativePath(fileName: r)) {
1007 pfx = currentDirectory();
1008 if (!pfx.endsWith(c: QLatin1Char('/')))
1009 pfx += QLatin1Char('/');
1010 }
1011 int slash = r.lastIndexOf(c: QLatin1Char('/'));
1012 if (slash != -1) {
1013 dirs.append(t: r.left(n: slash+1));
1014 r = r.mid(position: slash+1);
1015 } else {
1016 dirs.append(t: QString());
1017 }
1018
1019 QString pattern = QRegularExpression::wildcardToRegularExpression(str: r);
1020 QRegularExpression regex(pattern, QRegularExpression::DotMatchesEverythingOption);
1021 if (!regex.isValid()) {
1022 evalError(fL1S("section(): Encountered invalid wildcard expression '%1'.").arg(a: pattern));
1023 goto allfail;
1024 }
1025 for (int d = 0; d < dirs.size(); d++) {
1026 QString dir = dirs[d];
1027 QDir qdir(pfx + dir);
1028 for (int i = 0, count = int(qdir.count()); i < count; ++i) {
1029 if (qdir[i] == statics.strDot || qdir[i] == statics.strDotDot)
1030 continue;
1031 QString fname = dir + qdir[i];
1032 if (IoUtils::fileType(fileName: pfx + fname) == IoUtils::FileIsDir) {
1033 if (recursive)
1034 dirs.append(t: fname + QLatin1Char('/'));
1035 }
1036 if (regex.match(subject: qdir[i]).hasMatch())
1037 ret += ProString(fname).setSource(currentFileId());
1038 }
1039 }
1040 break;
1041 }
1042#ifdef PROEVALUATOR_FULL
1043 case E_PROMPT: {
1044 ProStringRoUser u1(args.at(i: 0), m_tmp1);
1045 QString msg = m_option->expandEnvVars(str: u1.str());
1046 bool decorate = true;
1047 if (args.size() == 2)
1048 decorate = isTrue(str: args.at(i: 1));
1049 if (decorate) {
1050 if (!msg.endsWith(c: QLatin1Char('?')))
1051 msg += QLatin1Char('?');
1052 fprintf(stderr, format: "Project PROMPT: %s ", qPrintable(msg));
1053 } else {
1054 fputs(qPrintable(msg), stderr);
1055 }
1056 QFile qfile;
1057 if (qfile.open(stdin, ioFlags: QIODevice::ReadOnly)) {
1058 QTextStream t(&qfile);
1059 const QString &line = t.readLine();
1060 if (t.atEnd()) {
1061 fputs(s: "\n", stderr);
1062 evalError(fL1S("Unexpected EOF."));
1063 return ReturnError;
1064 }
1065 ret = split_value_list(vals: QStringView(line));
1066 }
1067 break;
1068 }
1069#endif
1070 case E_REPLACE: {
1071 const QRegularExpression before(args.at(i: 1).toQString(), QRegularExpression::DotMatchesEverythingOption);
1072 if (!before.isValid()) {
1073 evalError(fL1S("replace(): Encountered invalid regular expression '%1'.").arg(a: before.pattern()));
1074 goto allfail;
1075 }
1076 ProStringRwUser u2(args.at(i: 2), m_tmp2);
1077 const QString &after = u2.str();
1078 const auto vals = values(variableName: map(var: args.at(i: 0)));
1079 for (const ProString &val : vals) {
1080 ProStringRwUser u1(val, m_tmp1);
1081 QString rstr = u1.str();
1082 QString copy = rstr; // Force a detach on modify
1083 rstr.replace(re: before, after);
1084 ret << u1.extract(s: rstr, other: u2);
1085 }
1086 break;
1087 }
1088 case E_SORT_DEPENDS:
1089 case E_RESOLVE_DEPENDS: {
1090 QHash<ProKey, QSet<ProKey> > dependencies;
1091 ProValueMap dependees;
1092 QMultiMap<int, ProString> rootSet;
1093 ProStringList orgList = values(variableName: args.at(i: 0).toKey());
1094 ProString prefix = args.size() < 2 ? ProString() : args.at(i: 1);
1095 ProString priosfx = args.size() < 4 ? ProString(".priority") : args.at(i: 3);
1096 populateDeps(deps: orgList, prefix,
1097 suffixes: args.size() < 3 ? ProStringList(ProString(".depends"))
1098 : split_value_list(vals: args.at(i: 2).toQStringView()),
1099 priosfx, dependencies, dependees, rootSet);
1100 while (!rootSet.isEmpty()) {
1101 QMultiMap<int, ProString>::iterator it = rootSet.begin();
1102 const ProString item = *it;
1103 rootSet.erase(it);
1104 if ((func_t == E_RESOLVE_DEPENDS) || orgList.contains(str: item))
1105 ret.prepend(t: item);
1106 for (const ProString &dep : std::as_const(t&: dependees[item.toKey()])) {
1107 QSet<ProKey> &dset = dependencies[dep.toKey()];
1108 dset.remove(value: item.toKey());
1109 if (dset.isEmpty())
1110 rootSet.insert(key: first(variableName: ProKey(prefix + dep + priosfx)).toInt(), value: dep);
1111 }
1112 }
1113 break;
1114 }
1115 case E_ENUMERATE_VARS: {
1116 QSet<ProString> keys;
1117 for (const ProValueMap &vmap : std::as_const(t&: m_valuemapStack))
1118 for (ProValueMap::ConstIterator it = vmap.constBegin(); it != vmap.constEnd(); ++it)
1119 keys.insert(value: it.key());
1120 ret.reserve(asize: keys.size());
1121 for (const ProString &key : std::as_const(t&: keys))
1122 ret << key;
1123 break; }
1124 case E_SHADOWED: {
1125 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1126 QString rstr = m_option->shadowedPath(fileName: resolvePath(fileName: u1.str()));
1127 if (!rstr.isEmpty())
1128 ret << u1.extract(s: rstr);
1129 break;
1130 }
1131 case E_ABSOLUTE_PATH: {
1132 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1133 ProStringRwUser u2(m_tmp2);
1134 QString baseDir = args.size() > 1
1135 ? IoUtils::resolvePath(baseDir: currentDirectory(), fileName: u2.set(args.at(i: 1)))
1136 : currentDirectory();
1137 QString rstr = u1.str().isEmpty() ? baseDir : IoUtils::resolvePath(baseDir, fileName: u1.str());
1138 ret << u1.extract(s: rstr, other: u2);
1139 break;
1140 }
1141 case E_RELATIVE_PATH: {
1142 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1143 ProStringRoUser u2(m_tmp2);
1144 QString baseDir = args.size() > 1
1145 ? IoUtils::resolvePath(baseDir: currentDirectory(), fileName: u2.set(args.at(i: 1)))
1146 : currentDirectory();
1147 QString absArg = u1.str().isEmpty() ? baseDir : IoUtils::resolvePath(baseDir, fileName: u1.str());
1148 QString rstr = QDir(baseDir).relativeFilePath(fileName: absArg);
1149 ret << u1.extract(s: rstr);
1150 break;
1151 }
1152 case E_CLEAN_PATH: {
1153 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1154 ret << u1.extract(s: QDir::cleanPath(path: u1.str()));
1155 break;
1156 }
1157 case E_SYSTEM_PATH: {
1158 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1159 QString rstr = u1.str();
1160#ifdef Q_OS_WIN
1161 rstr.replace(QLatin1Char('/'), QLatin1Char('\\'));
1162#else
1163 rstr.replace(before: QLatin1Char('\\'), after: QLatin1Char('/'));
1164#endif
1165 ret << u1.extract(s: rstr);
1166 break;
1167 }
1168 case E_SHELL_PATH: {
1169 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1170 QString rstr = u1.str();
1171 if (m_dirSep.startsWith(c: QLatin1Char('\\'))) {
1172 rstr.replace(before: QLatin1Char('/'), after: QLatin1Char('\\'));
1173 } else {
1174 rstr.replace(before: QLatin1Char('\\'), after: QLatin1Char('/'));
1175#ifdef Q_OS_WIN
1176 // Convert d:/foo/bar to msys-style /d/foo/bar.
1177 if (rstr.length() > 2 && rstr.at(1) == QLatin1Char(':') && rstr.at(2) == QLatin1Char('/')) {
1178 rstr[1] = rstr.at(0);
1179 rstr[0] = QLatin1Char('/');
1180 }
1181#endif
1182 }
1183 ret << u1.extract(s: rstr);
1184 break;
1185 }
1186 case E_SYSTEM_QUOTE: {
1187 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1188 ret << u1.extract(s: IoUtils::shellQuote(arg: u1.str()));
1189 break;
1190 }
1191 case E_SHELL_QUOTE: {
1192 ProStringRwUser u1(args.at(i: 0), m_tmp1);
1193 QString rstr = u1.str();
1194 if (m_dirSep.startsWith(c: QLatin1Char('\\')))
1195 rstr = IoUtils::shellQuoteWin(arg: rstr);
1196 else
1197 rstr = IoUtils::shellQuoteUnix(arg: rstr);
1198 ret << u1.extract(s: rstr);
1199 break;
1200 }
1201 case E_GETENV: {
1202 ProStringRoUser u1(args.at(i: 0), m_tmp1);
1203 ret << ProString(m_option->getEnv(u1.str()));
1204 break;
1205 }
1206#ifdef Q_OS_WIN
1207 case E_READ_REGISTRY: {
1208 HKEY tree;
1209 const auto par = args.at(0);
1210 if (!par.compare(QLatin1String("HKCU"), Qt::CaseInsensitive)
1211 || !par.compare(QLatin1String("HKEY_CURRENT_USER"), Qt::CaseInsensitive)) {
1212 tree = HKEY_CURRENT_USER;
1213 } else if (!par.compare(QLatin1String("HKLM"), Qt::CaseInsensitive)
1214 || !par.compare(QLatin1String("HKEY_LOCAL_MACHINE"), Qt::CaseInsensitive)) {
1215 tree = HKEY_LOCAL_MACHINE;
1216 } else {
1217 evalError(fL1S("read_registry(): invalid or unsupported registry tree %1.")
1218 .arg(par.toQStringView()));
1219 goto allfail;
1220 }
1221 int flags = 0;
1222 if (args.count() > 2) {
1223 const auto opt = args.at(2);
1224 if (opt == "32"
1225 || !opt.compare(QLatin1String("wow64_32key"), Qt::CaseInsensitive)) {
1226 flags = KEY_WOW64_32KEY;
1227 } else if (opt == "64"
1228 || !opt.compare(QLatin1String("wow64_64key"), Qt::CaseInsensitive)) {
1229 flags = KEY_WOW64_64KEY;
1230 } else {
1231 evalError(fL1S("read_registry(): invalid option %1.")
1232 .arg(opt.toQStringView()));
1233 goto allfail;
1234 }
1235 }
1236 ret << ProString(qt_readRegistryKey(tree, args.at(1).toQString(m_tmp1), flags));
1237 break;
1238 }
1239#endif
1240 default:
1241 evalError(fL1S("Function '%1' is not implemented.").arg(a: func.toQStringView()));
1242 break;
1243 }
1244
1245 allfail:
1246 return ReturnTrue;
1247}
1248
1249QMakeEvaluator::VisitReturn QMakeEvaluator::testFunc_cache(const ProStringList &args)
1250{
1251 bool persist = true;
1252 enum { TargetStash, TargetCache, TargetSuper } target = TargetCache;
1253 enum { CacheSet, CacheAdd, CacheSub } mode = CacheSet;
1254 ProKey srcvar;
1255 if (args.size() >= 2) {
1256 const auto opts = split_value_list(vals: args.at(i: 1).toQStringView());
1257 for (const ProString &opt : opts) {
1258 if (opt == QLatin1String("transient")) {
1259 persist = false;
1260 } else if (opt == QLatin1String("super")) {
1261 target = TargetSuper;
1262 } else if (opt == QLatin1String("stash")) {
1263 target = TargetStash;
1264 } else if (opt == QLatin1String("set")) {
1265 mode = CacheSet;
1266 } else if (opt == QLatin1String("add")) {
1267 mode = CacheAdd;
1268 } else if (opt == QLatin1String("sub")) {
1269 mode = CacheSub;
1270 } else {
1271 evalError(fL1S("cache(): invalid flag %1.").arg(a: opt.toQStringView()));
1272 return ReturnFalse;
1273 }
1274 }
1275 if (args.size() >= 3) {
1276 srcvar = args.at(i: 2).toKey();
1277 } else if (mode != CacheSet) {
1278 evalError(fL1S("cache(): modes other than 'set' require a source variable."));
1279 return ReturnFalse;
1280 }
1281 }
1282 QString varstr;
1283 ProKey dstvar = args.at(i: 0).toKey();
1284 if (!dstvar.isEmpty()) {
1285 if (srcvar.isEmpty())
1286 srcvar = dstvar;
1287 ProValueMap::Iterator srcvarIt;
1288 if (!findValues(variableName: srcvar, it: &srcvarIt)) {
1289 evalError(fL1S("Variable %1 is not defined.").arg(a: srcvar.toQStringView()));
1290 return ReturnFalse;
1291 }
1292 // The caches for the host and target may differ (e.g., when we are manipulating
1293 // CONFIG), so we cannot compute a common new value for both.
1294 const ProStringList &diffval = *srcvarIt;
1295 ProStringList newval;
1296 bool changed = false;
1297 for (bool hostBuild = false; ; hostBuild = true) {
1298#ifdef PROEVALUATOR_THREAD_SAFE
1299 m_option->mutex.lock();
1300#endif
1301 QMakeBaseEnv *baseEnv =
1302 m_option->baseEnvs.value(key: QMakeBaseKey(m_buildRoot, m_stashfile, hostBuild));
1303#ifdef PROEVALUATOR_THREAD_SAFE
1304 // It's ok to unlock this before locking baseEnv,
1305 // as we have no intention to initialize the env.
1306 m_option->mutex.unlock();
1307#endif
1308 do {
1309 if (!baseEnv)
1310 break;
1311#ifdef PROEVALUATOR_THREAD_SAFE
1312 QMutexLocker locker(&baseEnv->mutex);
1313 if (baseEnv->inProgress && baseEnv->evaluator != this) {
1314 // The env is still in the works, but it may be already past the cache
1315 // loading. So we need to wait for completion and amend it as usual.
1316 QThreadPool::globalInstance()->releaseThread();
1317 baseEnv->cond.wait(&baseEnv->mutex);
1318 QThreadPool::globalInstance()->reserveThread();
1319 }
1320 if (!baseEnv->isOk)
1321 break;
1322#endif
1323 QMakeEvaluator *baseEval = baseEnv->evaluator;
1324 const ProStringList &oldval = baseEval->values(variableName: dstvar);
1325 if (mode == CacheSet) {
1326 newval = diffval;
1327 } else {
1328 newval = oldval;
1329 if (mode == CacheAdd)
1330 newval += diffval;
1331 else
1332 newval.removeEach(value: diffval);
1333 }
1334 if (oldval != newval) {
1335 if (target != TargetStash || !m_stashfile.isEmpty()) {
1336 baseEval->valuesRef(variableName: dstvar) = newval;
1337 if (target == TargetSuper) {
1338 do {
1339 if (dstvar == QLatin1String("QMAKEPATH")) {
1340 baseEval->m_qmakepath = newval.toQStringList();
1341 baseEval->updateMkspecPaths();
1342 } else if (dstvar == QLatin1String("QMAKEFEATURES")) {
1343 baseEval->m_qmakefeatures = newval.toQStringList();
1344 } else {
1345 break;
1346 }
1347 baseEval->updateFeaturePaths();
1348 if (hostBuild == m_hostBuild)
1349 m_featureRoots = baseEval->m_featureRoots;
1350 } while (false);
1351 }
1352 }
1353 changed = true;
1354 }
1355 } while (false);
1356 if (hostBuild)
1357 break;
1358 }
1359 // We assume that whatever got the cached value to be what it is now will do so
1360 // the next time as well, so we just skip the persisting if nothing changed.
1361 if (!persist || !changed)
1362 return ReturnTrue;
1363 varstr = dstvar.toQString();
1364 if (mode == CacheAdd)
1365 varstr += QLatin1String(" +=");
1366 else if (mode == CacheSub)
1367 varstr += QLatin1String(" -=");
1368 else
1369 varstr += QLatin1String(" =");
1370 if (diffval.size() == 1) {
1371 varstr += QLatin1Char(' ');
1372 varstr += quoteValue(val: diffval.at(i: 0));
1373 } else if (!diffval.isEmpty()) {
1374 for (const ProString &vval : diffval) {
1375 varstr += QLatin1String(" \\\n ");
1376 varstr += quoteValue(val: vval);
1377 }
1378 }
1379 varstr += QLatin1Char('\n');
1380 }
1381 QString fn;
1382 QMakeVfs::VfsFlags flags = (m_cumulative ? QMakeVfs::VfsCumulative : QMakeVfs::VfsExact);
1383 if (target == TargetSuper) {
1384 if (m_superfile.isEmpty()) {
1385 m_superfile = QDir::cleanPath(path: m_outputDir + QLatin1String("/.qmake.super"));
1386 printf(format: "Info: creating super cache file %s\n", qPrintable(QDir::toNativeSeparators(m_superfile)));
1387 valuesRef(variableName: ProKey("_QMAKE_SUPER_CACHE_")) << ProString(m_superfile);
1388 }
1389 fn = m_superfile;
1390 } else if (target == TargetCache) {
1391 if (m_cachefile.isEmpty()) {
1392 m_cachefile = QDir::cleanPath(path: m_outputDir + QLatin1String("/.qmake.cache"));
1393 printf(format: "Info: creating cache file %s\n", qPrintable(QDir::toNativeSeparators(m_cachefile)));
1394 valuesRef(variableName: ProKey("_QMAKE_CACHE_")) << ProString(m_cachefile);
1395 // We could update m_{source,build}Root and m_featureRoots here, or even
1396 // "re-home" our rootEnv, but this doesn't sound too useful - if somebody
1397 // wanted qmake to find something in the build directory, he could have
1398 // done so "from the outside".
1399 // The sub-projects will find the new cache all by themselves.
1400 }
1401 fn = m_cachefile;
1402 } else {
1403 fn = m_stashfile;
1404 if (fn.isEmpty())
1405 fn = QDir::cleanPath(path: m_outputDir + QLatin1String("/.qmake.stash"));
1406 if (!m_vfs->exists(fn, flags)) {
1407 printf(format: "Info: creating stash file %s\n", qPrintable(QDir::toNativeSeparators(fn)));
1408 valuesRef(variableName: ProKey("_QMAKE_STASH_")) << ProString(fn);
1409 }
1410 }
1411 return writeFile(fL1S("cache "), fn, mode: QIODevice::Append, flags, contents: varstr);
1412}
1413
1414QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBuiltinConditional(
1415 const QMakeInternal::QMakeBuiltin &adef, const ProKey &function, const ProStringList &args)
1416{
1417 traceMsg(fmt: "calling built-in %s(%s)", dbgKey(function), dbgSepStrList(args));
1418 int asz = args.size() > 1 ? args.size() : args.at(i: 0).isEmpty() ? 0 : 1;
1419 if (asz < adef.minArgs || asz > adef.maxArgs) {
1420 evalError(msg: adef.usage);
1421 return ReturnFalse;
1422 }
1423
1424 int func_t = adef.index;
1425 switch (func_t) {
1426 case T_DEFINED: {
1427 const ProKey &var = args.at(i: 0).toKey();
1428 if (args.size() > 1) {
1429 if (args[1] == QLatin1String("test")) {
1430 return returnBool(b: m_functionDefs.testFunctions.contains(key: var));
1431 } else if (args[1] == QLatin1String("replace")) {
1432 return returnBool(b: m_functionDefs.replaceFunctions.contains(key: var));
1433 } else if (args[1] == QLatin1String("var")) {
1434 ProValueMap::Iterator it;
1435 return returnBool(b: findValues(variableName: var, it: &it));
1436 }
1437 evalError(fL1S("defined(function, type): unexpected type [%1].")
1438 .arg(a: args.at(i: 1).toQStringView()));
1439 return ReturnFalse;
1440 }
1441 return returnBool(b: m_functionDefs.replaceFunctions.contains(key: var)
1442 || m_functionDefs.testFunctions.contains(key: var));
1443 }
1444 case T_EXPORT: {
1445 const ProKey &var = map(var: args.at(i: 0));
1446 for (ProValueMapStack::iterator vmi = m_valuemapStack.end();
1447 --vmi != m_valuemapStack.begin(); ) {
1448 ProValueMap::Iterator it = (*vmi).find(key: var);
1449 if (it != (*vmi).end()) {
1450 if (it->constBegin() == statics.fakeValue.constBegin()) {
1451 // This is stupid, but qmake doesn't propagate deletions
1452 m_valuemapStack.front()[var] = ProStringList();
1453 } else {
1454 m_valuemapStack.front()[var] = *it;
1455 }
1456 (*vmi).erase(it);
1457 while (--vmi != m_valuemapStack.begin())
1458 (*vmi).remove(key: var);
1459 break;
1460 }
1461 }
1462 return ReturnTrue;
1463 }
1464 case T_DISCARD_FROM: {
1465 if (m_valuemapStack.size() != 1) {
1466 evalError(fL1S("discard_from() cannot be called from functions."));
1467 return ReturnFalse;
1468 }
1469 ProStringRoUser u1(args.at(i: 0), m_tmp1);
1470 QString fn = resolvePath(fileName: u1.str());
1471 QMakeVfs::VfsFlags flags = (m_cumulative ? QMakeVfs::VfsCumulative : QMakeVfs::VfsExact);
1472 int pro = m_vfs->idForFileName(fn, flags: flags | QMakeVfs::VfsAccessedOnly);
1473 if (!pro)
1474 return ReturnFalse;
1475 ProValueMap &vmap = m_valuemapStack.front();
1476 for (auto vit = vmap.begin(); vit != vmap.end(); ) {
1477 if (!vit->isEmpty()) {
1478 auto isFrom = [pro](const ProString &s) {
1479 return s.sourceFile() == pro;
1480 };
1481 vit->removeIf(pred: isFrom);
1482 if (vit->isEmpty()) {
1483 // When an initially non-empty variable becomes entirely empty,
1484 // undefine it altogether.
1485 vit = vmap.erase(it: vit);
1486 continue;
1487 }
1488 }
1489 ++vit;
1490 }
1491 for (auto fit = m_functionDefs.testFunctions.begin(); fit != m_functionDefs.testFunctions.end(); ) {
1492 if (fit->pro()->id() == pro)
1493 fit = m_functionDefs.testFunctions.erase(it: fit);
1494 else
1495 ++fit;
1496 }
1497 for (auto fit = m_functionDefs.replaceFunctions.begin(); fit != m_functionDefs.replaceFunctions.end(); ) {
1498 if (fit->pro()->id() == pro)
1499 fit = m_functionDefs.replaceFunctions.erase(it: fit);
1500 else
1501 ++fit;
1502 }
1503 ProStringList &iif = m_valuemapStack.front()[ProKey("QMAKE_INTERNAL_INCLUDED_FILES")];
1504 int idx = iif.indexOf(t: ProString(fn));
1505 if (idx >= 0)
1506 iif.removeAt(idx);
1507 return ReturnTrue;
1508 }
1509 case T_INFILE: {
1510 ProValueMap vars;
1511 QString fn = filePathEnvArg0(args);
1512 VisitReturn ok = evaluateFileInto(fileName: fn, values: &vars, flags: LoadProOnly);
1513 if (ok != ReturnTrue)
1514 return ok;
1515 if (args.size() == 2)
1516 return returnBool(b: vars.contains(key: map(var: args.at(i: 1))));
1517 QRegularExpression regx;
1518 regx.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
1519 ProStringRoUser u1(args.at(i: 2), m_tmp1);
1520 const QString &qry = u1.str();
1521 if (qry != QRegularExpression::escape(str: qry)) {
1522 regx.setPattern(QRegularExpression::anchoredPattern(expression: qry));
1523 if (!regx.isValid()) {
1524 evalError(fL1S("infile(): Encountered invalid regular expression '%1'.").arg(a: qry));
1525 return ReturnFalse;
1526 }
1527 }
1528 const auto strings = vars.value(key: map(var: args.at(i: 1)));
1529 for (const ProString &s : strings) {
1530 if (s == qry)
1531 return ReturnTrue;
1532 if (!regx.pattern().isEmpty()) {
1533 ProStringRoUser u2(s, m_tmp[m_toggle ^= 1]);
1534 if (regx.match(subject: u2.str()).hasMatch())
1535 return ReturnTrue;
1536 }
1537 }
1538 return ReturnFalse;
1539 }
1540 case T_REQUIRES:
1541#ifdef PROEVALUATOR_FULL
1542 if (checkRequirements(deps: args) == ReturnError)
1543 return ReturnError;
1544#endif
1545 return ReturnFalse; // Another qmake breakage
1546 case T_EVAL: {
1547 VisitReturn ret = ReturnFalse;
1548 QString contents = args.join(sep: statics.field_sep);
1549 ProFile *pro = m_parser->parsedProBlock(contents: QStringView(contents),
1550 id: 0, name: m_current.pro->fileName(), line: m_current.line);
1551 if (m_cumulative || pro->isOk()) {
1552 m_locationStack.push(t: m_current);
1553 visitProBlock(pro, tokPtr: pro->tokPtr());
1554 ret = ReturnTrue; // This return value is not too useful, but that's qmake
1555 m_current = m_locationStack.pop();
1556 }
1557 pro->deref();
1558 return ret;
1559 }
1560 case T_IF: {
1561 return evaluateConditional(cond: args.at(i: 0).toQStringView(),
1562 where: m_current.pro->fileName(), line: m_current.line);
1563 }
1564 case T_CONFIG: {
1565 if (args.size() == 1)
1566 return returnBool(b: isActiveConfig(config: args.at(i: 0).toQStringView()));
1567 const auto mutuals = args.at(i: 1).toQStringView().split(sep: QLatin1Char('|'),
1568 behavior: Qt::SkipEmptyParts);
1569 const ProStringList &configs = values(variableName: statics.strCONFIG);
1570
1571 for (int i = configs.size() - 1; i >= 0; i--) {
1572 for (int mut = 0; mut < mutuals.size(); mut++) {
1573 if (configs[i].toQStringView() == mutuals[mut].trimmed())
1574 return returnBool(b: configs[i] == args[0]);
1575 }
1576 }
1577 return ReturnFalse;
1578 }
1579 case T_CONTAINS: {
1580 ProStringRoUser u1(args.at(i: 1), m_tmp1);
1581 const QString &qry = u1.str();
1582 QRegularExpression regx;
1583 regx.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
1584 if (qry != QRegularExpression::escape(str: qry)) {
1585 regx.setPattern(QRegularExpression::anchoredPattern(expression: qry));
1586 if (!regx.isValid()) {
1587 evalError(fL1S("contains(): Encountered invalid regular expression '%1'.").arg(a: qry));
1588 return ReturnFalse;
1589 }
1590 }
1591 const ProStringList &l = values(variableName: map(var: args.at(i: 0)));
1592 if (args.size() == 2) {
1593 for (int i = 0; i < l.size(); ++i) {
1594 const ProString &val = l[i];
1595 if (val == qry)
1596 return ReturnTrue;
1597 if (!regx.pattern().isEmpty()) {
1598 ProStringRoUser u2(val, m_tmp[m_toggle ^= 1]);
1599 if (regx.match(subject: u2.str()).hasMatch())
1600 return ReturnTrue;
1601 }
1602 }
1603 } else {
1604 const auto mutuals = args.at(i: 2).toQStringView().split(sep: QLatin1Char('|'),
1605 behavior: Qt::SkipEmptyParts);
1606 for (int i = l.size() - 1; i >= 0; i--) {
1607 const ProString &val = l[i];
1608 for (int mut = 0; mut < mutuals.size(); mut++) {
1609 if (val.toQStringView() == mutuals[mut].trimmed()) {
1610 if (val == qry)
1611 return ReturnTrue;
1612 if (!regx.pattern().isEmpty()) {
1613 ProStringRoUser u2(val, m_tmp[m_toggle ^= 1]);
1614 if (regx.match(subject: u2.str()).hasMatch())
1615 return ReturnTrue;
1616 }
1617 return ReturnFalse;
1618 }
1619 }
1620 }
1621 }
1622 return ReturnFalse;
1623 }
1624 case T_COUNT: {
1625 int cnt = values(variableName: map(var: args.at(i: 0))).size();
1626 int val = args.at(i: 1).toInt();
1627 if (args.size() == 3) {
1628 const ProString &comp = args.at(i: 2);
1629 if (comp == QLatin1String(">") || comp == QLatin1String("greaterThan")) {
1630 return returnBool(b: cnt > val);
1631 } else if (comp == QLatin1String(">=")) {
1632 return returnBool(b: cnt >= val);
1633 } else if (comp == QLatin1String("<") || comp == QLatin1String("lessThan")) {
1634 return returnBool(b: cnt < val);
1635 } else if (comp == QLatin1String("<=")) {
1636 return returnBool(b: cnt <= val);
1637 } else if (comp == QLatin1String("equals") || comp == QLatin1String("isEqual")
1638 || comp == QLatin1String("=") || comp == QLatin1String("==")) {
1639 // fallthrough
1640 } else {
1641 evalError(fL1S("Unexpected modifier to count(%2).").arg(a: comp.toQStringView()));
1642 return ReturnFalse;
1643 }
1644 }
1645 return returnBool(b: cnt == val);
1646 }
1647 case T_GREATERTHAN:
1648 case T_LESSTHAN: {
1649 const ProString &rhs = args.at(i: 1);
1650 const QString &lhs = values(variableName: map(var: args.at(i: 0))).join(sep: statics.field_sep);
1651 bool ok;
1652 int rhs_int = rhs.toInt(ok: &ok);
1653 if (ok) { // do integer compare
1654 int lhs_int = lhs.toInt(ok: &ok);
1655 if (ok) {
1656 if (func_t == T_GREATERTHAN)
1657 return returnBool(b: lhs_int > rhs_int);
1658 return returnBool(b: lhs_int < rhs_int);
1659 }
1660 }
1661 if (func_t == T_GREATERTHAN)
1662 return returnBool(b: lhs > rhs.toQStringView());
1663 return returnBool(b: lhs < rhs.toQStringView());
1664 }
1665 case T_EQUALS:
1666 return returnBool(b: values(variableName: map(var: args.at(i: 0))).join(sep: statics.field_sep)
1667 == args.at(i: 1).toQStringView());
1668 case T_VERSION_AT_LEAST:
1669 case T_VERSION_AT_MOST: {
1670 const QVersionNumber lvn = QVersionNumber::fromString(string: values(variableName: args.at(i: 0).toKey()).join(sep: QLatin1Char('.')));
1671 const QVersionNumber rvn = QVersionNumber::fromString(string: args.at(i: 1).toQStringView());
1672 if (func_t == T_VERSION_AT_LEAST)
1673 return returnBool(b: lvn >= rvn);
1674 return returnBool(b: lvn <= rvn);
1675 }
1676 case T_CLEAR: {
1677 ProValueMap *hsh;
1678 ProValueMap::Iterator it;
1679 const ProKey &var = map(var: args.at(i: 0));
1680 if (!(hsh = findValues(variableName: var, it: &it)))
1681 return ReturnFalse;
1682 if (hsh == &m_valuemapStack.top())
1683 it->clear();
1684 else
1685 m_valuemapStack.top()[var].clear();
1686 return ReturnTrue;
1687 }
1688 case T_UNSET: {
1689 ProValueMap *hsh;
1690 ProValueMap::Iterator it;
1691 const ProKey &var = map(var: args.at(i: 0));
1692 if (!(hsh = findValues(variableName: var, it: &it)))
1693 return ReturnFalse;
1694 if (m_valuemapStack.size() == 1)
1695 hsh->erase(it);
1696 else if (hsh == &m_valuemapStack.top())
1697 *it = statics.fakeValue;
1698 else
1699 m_valuemapStack.top()[var] = statics.fakeValue;
1700 return ReturnTrue;
1701 }
1702 case T_PARSE_JSON: {
1703 QByteArray json = values(variableName: args.at(i: 0).toKey()).join(sep: QLatin1Char(' ')).toUtf8();
1704 ProStringRoUser u1(args.at(i: 1), m_tmp2);
1705 QString parseInto = u1.str();
1706 return parseJsonInto(json, into: parseInto, value: &m_valuemapStack.top());
1707 }
1708 case T_INCLUDE: {
1709 QString parseInto;
1710 LoadFlags flags;
1711 if (m_cumulative)
1712 flags = LoadSilent;
1713 if (args.size() >= 2) {
1714 if (!args.at(i: 1).isEmpty())
1715 parseInto = args.at(i: 1) + QLatin1Char('.');
1716 if (args.size() >= 3 && isTrue(str: args.at(i: 2)))
1717 flags = LoadSilent;
1718 }
1719 QString fn = filePathEnvArg0(args);
1720 VisitReturn ok;
1721 if (parseInto.isEmpty()) {
1722 ok = evaluateFileChecked(fileName: fn, type: QMakeHandler::EvalIncludeFile, flags: LoadProOnly | flags);
1723 } else {
1724 ProValueMap symbols;
1725 if ((ok = evaluateFileInto(fileName: fn, values: &symbols, flags: LoadAll | flags)) == ReturnTrue) {
1726 ProValueMap newMap;
1727 for (ProValueMap::ConstIterator
1728 it = m_valuemapStack.top().constBegin(),
1729 end = m_valuemapStack.top().constEnd();
1730 it != end; ++it) {
1731 const ProString &ky = it.key();
1732 if (!ky.startsWith(sub: parseInto))
1733 newMap[it.key()] = it.value();
1734 }
1735 for (ProValueMap::ConstIterator it = symbols.constBegin();
1736 it != symbols.constEnd(); ++it) {
1737 if (!it.key().startsWith(c: QLatin1Char('.')))
1738 newMap.insert(key: ProKey(parseInto + it.key()), value: it.value());
1739 }
1740 m_valuemapStack.top() = newMap;
1741 }
1742 }
1743 if (ok == ReturnFalse && (flags & LoadSilent))
1744 ok = ReturnTrue;
1745 return ok;
1746 }
1747 case T_LOAD: {
1748 bool ignore_error = (args.size() == 2 && isTrue(str: args.at(i: 1)));
1749 VisitReturn ok = evaluateFeatureFile(fileName: m_option->expandEnvVars(str: args.at(i: 0).toQString()),
1750 silent: ignore_error);
1751 if (ok == ReturnFalse && ignore_error)
1752 ok = ReturnTrue;
1753 return ok;
1754 }
1755 case T_DEBUG: {
1756#ifdef PROEVALUATOR_DEBUG
1757 int level = args.at(i: 0).toInt();
1758 if (level <= m_debugLevel) {
1759 ProStringRoUser u1(args.at(i: 1), m_tmp1);
1760 const QString &msg = m_option->expandEnvVars(str: u1.str());
1761 debugMsg(level, fmt: "Project DEBUG: %s", qPrintable(msg));
1762 }
1763#endif
1764 return ReturnTrue;
1765 }
1766 case T_LOG:
1767 case T_ERROR:
1768 case T_WARNING:
1769 case T_MESSAGE: {
1770 ProStringRoUser u1(args.at(i: 0), m_tmp1);
1771 const QString &msg = m_option->expandEnvVars(str: u1.str());
1772 if (!m_skipLevel) {
1773 if (func_t == T_LOG) {
1774#ifdef PROEVALUATOR_FULL
1775 fputs(s: msg.toLatin1().constData(), stderr);
1776#endif
1777 } else if (!msg.isEmpty() || func_t != T_ERROR) {
1778 ProStringRoUser u2(function, m_tmp2);
1779 m_handler->fileMessage(
1780 type: (func_t == T_ERROR ? QMakeHandler::ErrorMessage :
1781 func_t == T_WARNING ? QMakeHandler::WarningMessage :
1782 QMakeHandler::InfoMessage)
1783 | (m_cumulative ? QMakeHandler::CumulativeEvalMessage : 0),
1784 fL1S("Project %1: %2").arg(args: u2.str().toUpper(), args: msg));
1785 }
1786 }
1787 return (func_t == T_ERROR && !m_cumulative) ? ReturnError : ReturnTrue;
1788 }
1789 case T_SYSTEM: {
1790#ifdef PROEVALUATOR_FULL
1791 if (m_cumulative) // Anything else would be insanity
1792 return ReturnFalse;
1793#if QT_CONFIG(process)
1794 QProcess proc;
1795 proc.setProcessChannelMode(QProcess::ForwardedChannels);
1796 runProcess(proc: &proc, command: args.at(i: 0).toQString());
1797 return returnBool(b: proc.exitStatus() == QProcess::NormalExit && proc.exitCode() == 0);
1798#else
1799 int ec = system((QLatin1String("cd ")
1800 + IoUtils::shellQuote(QDir::toNativeSeparators(currentDirectory()))
1801 + QLatin1String(" && ") + args.at(0)).toLocal8Bit().constData());
1802# ifdef Q_OS_UNIX
1803 if (ec != -1 && WIFSIGNALED(ec) && (WTERMSIG(ec) == SIGQUIT || WTERMSIG(ec) == SIGINT))
1804 raise(WTERMSIG(ec));
1805# endif
1806 return returnBool(ec == 0);
1807#endif
1808#else
1809 return ReturnTrue;
1810#endif
1811 }
1812 case T_ISEMPTY: {
1813 return returnBool(b: values(variableName: map(var: args.at(i: 0))).isEmpty());
1814 }
1815 case T_EXISTS: {
1816 QString file = filePathEnvArg0(args);
1817 // Don't use VFS here:
1818 // - it supports neither listing nor even directories
1819 // - it's unlikely that somebody would test for files they created themselves
1820 if (IoUtils::exists(fileName: file))
1821 return ReturnTrue;
1822 int slsh = file.lastIndexOf(c: QLatin1Char('/'));
1823 QString fn = file.mid(position: slsh+1);
1824 if (fn.contains(c: QLatin1Char('*')) || fn.contains(c: QLatin1Char('?'))) {
1825 QString dirstr = file.left(n: slsh+1);
1826 dirstr.detach();
1827 if (!QDir(dirstr).entryList(nameFilters: QStringList(fn)).isEmpty())
1828 return ReturnTrue;
1829 }
1830
1831 return ReturnFalse;
1832 }
1833 case T_MKPATH: {
1834#ifdef PROEVALUATOR_FULL
1835 QString fn = filePathArg0(args);
1836 if (!QDir::current().mkpath(dirPath: fn)) {
1837 evalError(fL1S("Cannot create directory %1.").arg(a: QDir::toNativeSeparators(pathName: fn)));
1838 return ReturnFalse;
1839 }
1840#endif
1841 return ReturnTrue;
1842 }
1843 case T_WRITE_FILE: {
1844 QIODevice::OpenMode mode = QIODevice::Truncate;
1845 QMakeVfs::VfsFlags flags = (m_cumulative ? QMakeVfs::VfsCumulative : QMakeVfs::VfsExact);
1846 QString contents;
1847 if (args.size() >= 2) {
1848 const ProStringList &vals = values(variableName: args.at(i: 1).toKey());
1849 if (!vals.isEmpty())
1850 contents = vals.join(sep: QLatin1Char('\n')) + QLatin1Char('\n');
1851 if (args.size() >= 3) {
1852 const auto opts = split_value_list(vals: args.at(i: 2).toQStringView());
1853 for (const ProString &opt : opts) {
1854 if (opt == QLatin1String("append")) {
1855 mode = QIODevice::Append;
1856 } else if (opt == QLatin1String("exe")) {
1857 flags |= QMakeVfs::VfsExecutable;
1858 } else {
1859 evalError(fL1S("write_file(): invalid flag %1.").arg(a: opt.toQStringView()));
1860 return ReturnFalse;
1861 }
1862 }
1863 }
1864 }
1865 QString path = filePathArg0(args);
1866 return writeFile(ctx: QString(), fn: path, mode, flags, contents);
1867 }
1868 case T_TOUCH: {
1869#ifdef PROEVALUATOR_FULL
1870 ProStringRoUser u1(args.at(i: 0), m_tmp1);
1871 ProStringRoUser u2(args.at(i: 1), m_tmp2);
1872 const QString &tfn = resolvePath(fileName: u1.str());
1873 const QString &rfn = resolvePath(fileName: u2.str());
1874 QString error;
1875 if (!IoUtils::touchFile(targetFileName: tfn, referenceFileName: rfn, errorString: &error)) {
1876 evalError(msg: error);
1877 return ReturnFalse;
1878 }
1879#endif
1880 return ReturnTrue;
1881 }
1882 case T_CACHE:
1883 return testFunc_cache(args);
1884 case T_RELOAD_PROPERTIES:
1885#ifdef QT_BUILD_QMAKE
1886 m_option->reloadProperties();
1887#endif
1888 return ReturnTrue;
1889 default:
1890 evalError(fL1S("Function '%1' is not implemented.").arg(a: function.toQStringView()));
1891 return ReturnFalse;
1892 }
1893}
1894
1895QT_END_NAMESPACE
1896

source code of qtbase/qmake/library/qmakebuiltins.cpp