Coverage Report

Created: 2026-09-14 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmFileAPI.cxx
Line
Count
Source
1
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2
   file LICENSE.rst or https://cmake.org/licensing for details.  */
3
#include "cmFileAPI.h"
4
5
#include <algorithm>
6
#include <cassert>
7
#include <chrono>
8
#include <ctime>
9
#include <functional>
10
#include <iomanip>
11
#include <iterator>
12
#include <sstream>
13
#include <utility>
14
15
#include <cm/optional>
16
#include <cmext/string_view>
17
18
#include "cmsys/Directory.hxx"
19
#include "cmsys/FStream.hxx"
20
21
#include "cmCryptoHash.h"
22
#include "cmFileAPICMakeFiles.h"
23
#include "cmFileAPICache.h"
24
#include "cmFileAPICodemodel.h"
25
#include "cmFileAPIConfigureLog.h"
26
#include "cmFileAPIToolchains.h"
27
#include "cmGlobalGenerator.h"
28
#include "cmJSONState.h"
29
#include "cmStringAlgorithms.h"
30
#include "cmSystemTools.h"
31
#include "cmTimestamp.h"
32
#include "cmUnreachable.h"
33
#include "cmake.h"
34
35
#if defined(__clang__) && defined(__has_warning)
36
#  if __has_warning("-Wrange-loop-analysis")
37
#    if defined(__apple_build_version__)
38
#      if __apple_build_version__ < 13000000
39
#        define CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
40
#      endif
41
#    else
42
#      if __clang_major__ < 11
43
#        define CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
44
#      endif
45
#    endif
46
#  endif
47
#endif
48
49
cmFileAPI::cmFileAPI(cmake* cm)
50
0
  : CMakeInstance(cm)
51
0
{
52
0
  this->APIv1 =
53
0
    cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/.cmake/api/v1");
54
55
0
  if (cm::optional<std::string> cmakeConfigDir =
56
0
        cmSystemTools::GetCMakeConfigDirectory()) {
57
0
    this->UserAPIv1 = cmStrCat(std::move(*cmakeConfigDir), "/api/v1"_s);
58
0
  }
59
60
0
  Json::StreamWriterBuilder wbuilder;
61
0
  wbuilder["indentation"] = "\t";
62
0
  this->JsonWriter =
63
0
    std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
64
0
}
65
66
void cmFileAPI::ReadQueries()
67
0
{
68
0
  std::string const query_dir = cmStrCat(this->APIv1, "/query");
69
0
  std::string const user_query_dir = cmStrCat(this->UserAPIv1, "/query");
70
0
  this->QueryExists =
71
0
    this->QueryExists || cmSystemTools::FileIsDirectory(query_dir);
72
0
  if (!this->UserAPIv1.empty()) {
73
0
    this->QueryExists =
74
0
      this->QueryExists || cmSystemTools::FileIsDirectory(user_query_dir);
75
0
  }
76
0
  if (!this->QueryExists) {
77
0
    return;
78
0
  }
79
80
  // Load queries at the top level.
81
0
  std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
82
0
  if (!this->UserAPIv1.empty()) {
83
0
    std::vector<std::string> user_queries = cmFileAPI::LoadDir(user_query_dir);
84
0
    std::move(user_queries.begin(), user_queries.end(),
85
0
              std::back_inserter(queries));
86
0
  }
87
88
  // Read the queries and save for later.
89
0
  for (std::string& query : queries) {
90
0
    if (cmHasLiteralPrefix(query, "client-")) {
91
0
      this->ReadClient(query);
92
0
    } else if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
93
0
      this->TopQuery.Unknown.push_back(std::move(query));
94
0
    }
95
0
  }
96
0
}
97
98
std::vector<unsigned int> cmFileAPI::GetConfigureLogVersions()
99
0
{
100
0
  std::vector<unsigned int> versions;
101
0
  auto getConfigureLogVersions = [&versions](Query const& q) {
102
#ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
103
#  pragma clang diagnostic push
104
#  pragma clang diagnostic ignored "-Wrange-loop-analysis"
105
#endif
106
0
    for (Object const o : q.Known) {
107
#ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
108
#  pragma clang diagnostic pop
109
#endif
110
0
      if (o.Kind == ObjectKind::ConfigureLog) {
111
0
        versions.emplace_back(o.Version);
112
0
      }
113
0
    }
114
0
  };
115
0
  getConfigureLogVersions(this->TopQuery);
116
0
  for (auto const& client : this->ClientQueries) {
117
0
    getConfigureLogVersions(client.second.DirQuery);
118
0
  }
119
0
  std::sort(versions.begin(), versions.end());
120
0
  versions.erase(std::unique(versions.begin(), versions.end()),
121
0
                 versions.end());
122
0
  return versions;
123
0
}
124
125
void cmFileAPI::WriteReplies(IndexFor indexFor)
126
0
{
127
0
  bool const success = indexFor == IndexFor::Success;
128
0
  this->ReplyIndexFor = indexFor;
129
130
0
  if (this->QueryExists) {
131
0
    cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
132
0
    this->WriteJsonFile(this->BuildReplyIndex(), success ? "index" : "error",
133
0
                        ComputeSuffixTime);
134
0
  }
135
136
0
  if (success) {
137
0
    this->RemoveOldReplyFiles();
138
0
  }
139
0
}
140
141
std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
142
0
{
143
0
  std::vector<std::string> files;
144
0
  cmsys::Directory d;
145
0
  d.Load(dir);
146
0
  files.reserve(d.GetNumberOfFiles());
147
0
  for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
148
0
    std::string const& f = d.GetFileName(i);
149
0
    if (f != "." && f != "..") {
150
0
      files.push_back(f);
151
0
    }
152
0
  }
153
0
  std::sort(files.begin(), files.end());
154
0
  return files;
155
0
}
156
157
void cmFileAPI::RemoveOldReplyFiles()
158
0
{
159
0
  std::string const reply_dir = this->APIv1 + "/reply";
160
0
  std::vector<std::string> const files = this->LoadDir(reply_dir);
161
162
  // Reply names embed the configuration verbatim, so on a case-insensitive
163
  // filesystem a "debug" reply can alias a just-written "Debug" one; deleting
164
  // by name would strip a file the index still cites.  Decide by identity.
165
0
  std::vector<std::string> const toRemove =
166
0
    cmFileAPI::FilesToRemove<cmSystemTools::FileId>(
167
0
      files, this->ReplyFiles,
168
0
      [&reply_dir](std::string const& name,
169
0
                   cmSystemTools::FileId& id) -> bool {
170
0
        return cmSystemTools::GetFileId(cmStrCat(reply_dir, '/', name), id);
171
0
      });
172
0
  for (std::string const& f : toRemove) {
173
0
    cmSystemTools::RemoveFile(cmStrCat(reply_dir, '/', f));
174
0
  }
175
0
}
176
177
bool cmFileAPI::ReadJsonFile(std::string const& file, Json::Value& value,
178
                             std::string& error)
179
0
{
180
  // Verify the file exists.
181
0
  if (!cmSystemTools::FileExists(file) ||
182
0
      cmSystemTools::FileIsDirectory(file)) {
183
0
    value = Json::Value();
184
0
    error = "failed to read from file";
185
0
    return false;
186
0
  }
187
188
  // Parse our buffer as json.
189
0
  cmJSONState parseState(file, &value);
190
0
  if (!parseState.errors.empty()) {
191
0
    value = Json::Value();
192
0
    error = parseState.GetErrorMessage();
193
0
    return false;
194
0
  }
195
196
0
  return true;
197
0
}
198
199
std::string cmFileAPI::WriteJsonFile(
200
  Json::Value const& value, std::string const& prefix,
201
  std::string (*computeSuffix)(std::string const&))
202
0
{
203
0
  std::string fileName;
204
205
  // Write the json file with a temporary name.
206
0
  std::string const& tmpFile = this->APIv1 + "/tmp.json";
207
0
  cmsys::ofstream ftmp(tmpFile.c_str());
208
0
  this->JsonWriter->write(value, &ftmp);
209
0
  ftmp << "\n";
210
0
  ftmp.close();
211
0
  if (!ftmp) {
212
0
    cmSystemTools::RemoveFile(tmpFile);
213
0
    return fileName;
214
0
  }
215
216
  // Compute the final name for the file.
217
0
  std::string suffix = computeSuffix(tmpFile);
218
0
  std::string suffixWithExtension = cmStrCat('-', suffix, ".json");
219
0
  fileName = cmStrCat(prefix, suffixWithExtension);
220
221
  // Truncate the file name length
222
  // eCryptFS has a maximal file name length recommendation of 140
223
0
  size_t const maxFileNameLength = 140;
224
0
  size_t const fileNameLength = fileName.size();
225
0
  if (fileNameLength > maxFileNameLength) {
226
0
    size_t const newHashLength = 20;
227
0
    size_t const newSuffixLength =
228
0
      suffixWithExtension.size() - suffix.size() + newHashLength;
229
0
    size_t const overLength =
230
0
      fileNameLength - maxFileNameLength + newSuffixLength;
231
0
    size_t const startPos = fileNameLength - overLength;
232
0
    std::string const toBeRemoved = fileName.substr(startPos, overLength);
233
0
    suffix = cmCryptoHash(cmCryptoHash::AlgoSHA256)
234
0
               .HashString(toBeRemoved)
235
0
               .substr(0, newHashLength);
236
0
    suffixWithExtension = cmStrCat('-', suffix, ".json");
237
0
    fileName.replace(startPos, overLength, suffixWithExtension);
238
0
  }
239
240
  // Create the destination.
241
0
  std::string file = this->APIv1 + "/reply";
242
0
  cmSystemTools::MakeDirectory(file);
243
0
  file += "/";
244
0
  file += fileName;
245
246
  // If the final name already exists then assume it has proper content.
247
  // Otherwise, atomically place the reply file at its final name
248
0
  if (cmSystemTools::FileExists(file, true) ||
249
0
      !cmSystemTools::RenameFile(tmpFile, file)) {
250
0
    cmSystemTools::RemoveFile(tmpFile);
251
0
  }
252
253
  // Record this among files we have just written.
254
0
  this->ReplyFiles.insert(fileName);
255
256
0
  return fileName;
257
0
}
258
259
Json::Value cmFileAPI::MaybeJsonFile(Json::Value in, std::string const& prefix)
260
0
{
261
0
  Json::Value out;
262
0
  if (in.isObject() || in.isArray()) {
263
0
    out = Json::objectValue;
264
0
    out["jsonFile"] = this->WriteJsonFile(in, prefix);
265
0
  } else {
266
0
    out = std::move(in);
267
0
  }
268
0
  return out;
269
0
}
270
271
std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
272
0
{
273
0
  cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
274
0
  std::string hash = hasher.HashFile(file);
275
0
  hash.resize(20, '0');
276
0
  return hash;
277
0
}
278
279
std::string cmFileAPI::ComputeSuffixTime(std::string const&)
280
0
{
281
0
  std::chrono::milliseconds ms =
282
0
    std::chrono::duration_cast<std::chrono::milliseconds>(
283
0
      std::chrono::system_clock::now().time_since_epoch());
284
0
  std::chrono::seconds s =
285
0
    std::chrono::duration_cast<std::chrono::seconds>(ms);
286
287
0
  std::time_t ts = s.count();
288
0
  std::size_t tms = ms.count() % 1000;
289
290
0
  cmTimestamp cmts;
291
0
  std::ostringstream ss;
292
0
  ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
293
0
     << std::setfill('0') << std::setw(4) << tms;
294
0
  return ss.str();
295
0
}
296
297
bool cmFileAPI::ReadQuery(std::string const& query,
298
                          std::vector<Object>& objects)
299
0
{
300
  // Parse the "<kind>-" syntax.
301
0
  std::string::size_type sep_pos = query.find('-');
302
0
  if (sep_pos == std::string::npos) {
303
0
    return false;
304
0
  }
305
0
  std::string kindName = query.substr(0, sep_pos);
306
0
  std::string verStr = query.substr(sep_pos + 1);
307
0
  if (kindName == ObjectKindName(ObjectKind::CodeModel)) {
308
0
    Object o;
309
0
    o.Kind = ObjectKind::CodeModel;
310
0
    if (verStr == "v2") {
311
0
      o.Version = 2;
312
0
    } else {
313
0
      return false;
314
0
    }
315
0
    objects.push_back(o);
316
0
    return true;
317
0
  }
318
0
  if (kindName == ObjectKindName(ObjectKind::ConfigureLog)) {
319
0
    Object o;
320
0
    o.Kind = ObjectKind::ConfigureLog;
321
0
    if (verStr == "v1") {
322
0
      o.Version = 1;
323
0
    } else {
324
0
      return false;
325
0
    }
326
0
    objects.push_back(o);
327
0
    return true;
328
0
  }
329
0
  if (kindName == ObjectKindName(ObjectKind::Cache)) {
330
0
    Object o;
331
0
    o.Kind = ObjectKind::Cache;
332
0
    if (verStr == "v2") {
333
0
      o.Version = 2;
334
0
    } else {
335
0
      return false;
336
0
    }
337
0
    objects.push_back(o);
338
0
    return true;
339
0
  }
340
0
  if (kindName == ObjectKindName(ObjectKind::CMakeFiles)) {
341
0
    Object o;
342
0
    o.Kind = ObjectKind::CMakeFiles;
343
0
    if (verStr == "v1") {
344
0
      o.Version = 1;
345
0
    } else {
346
0
      return false;
347
0
    }
348
0
    objects.push_back(o);
349
0
    return true;
350
0
  }
351
0
  if (kindName == ObjectKindName(ObjectKind::Toolchains)) {
352
0
    Object o;
353
0
    o.Kind = ObjectKind::Toolchains;
354
0
    if (verStr == "v1") {
355
0
      o.Version = 1;
356
0
    } else {
357
0
      return false;
358
0
    }
359
0
    objects.push_back(o);
360
0
    return true;
361
0
  }
362
0
  if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
363
0
    Object o;
364
0
    o.Kind = ObjectKind::InternalTest;
365
0
    if (verStr == "v1") {
366
0
      o.Version = 1;
367
0
    } else if (verStr == "v2") {
368
0
      o.Version = 2;
369
0
    } else {
370
0
      return false;
371
0
    }
372
0
    objects.push_back(o);
373
0
    return true;
374
0
  }
375
0
  return false;
376
0
}
377
378
void cmFileAPI::ReadClient(std::string const& client)
379
0
{
380
  // Load queries for the client.
381
0
  std::string clientDir = cmStrCat(this->APIv1, "/query/", client);
382
0
  std::vector<std::string> queries = this->LoadDir(clientDir);
383
384
  // Read the queries and save for later.
385
0
  ClientQuery& clientQuery = this->ClientQueries[client];
386
0
  for (std::string& query : queries) {
387
0
    if (query == "query.json") {
388
0
      clientQuery.HaveQueryJson = true;
389
0
      this->ReadClientQuery(client, clientQuery.QueryJson);
390
0
    } else if (!this->ReadQuery(query, clientQuery.DirQuery.Known)) {
391
0
      clientQuery.DirQuery.Unknown.push_back(std::move(query));
392
0
    }
393
0
  }
394
0
}
395
396
void cmFileAPI::ReadClientQuery(std::string const& client, ClientQueryJson& q)
397
0
{
398
  // Read the query.json file.
399
0
  std::string queryFile =
400
0
    cmStrCat(this->APIv1, "/query/", client, "/query.json");
401
0
  Json::Value query;
402
0
  if (!this->ReadJsonFile(queryFile, query, q.Error)) {
403
0
    return;
404
0
  }
405
0
  if (!query.isObject()) {
406
0
    q.Error = "query root is not an object";
407
0
    return;
408
0
  }
409
410
0
  Json::Value const& clientValue = query["client"];
411
0
  if (!clientValue.isNull()) {
412
0
    q.ClientValue = clientValue;
413
0
  }
414
0
  q.RequestsValue = std::move(query["requests"]);
415
0
  q.Requests = this->BuildClientRequests(q.RequestsValue);
416
0
}
417
418
Json::Value cmFileAPI::BuildReplyIndex()
419
0
{
420
0
  Json::Value index(Json::objectValue);
421
422
  // Report information about this version of CMake.
423
0
  index["cmake"] = this->BuildCMake();
424
425
  // Reply to all queries that we loaded.
426
0
  Json::Value& reply = index["reply"] = this->BuildReply(this->TopQuery);
427
0
  for (auto const& client : this->ClientQueries) {
428
0
    std::string const& clientName = client.first;
429
0
    ClientQuery const& clientQuery = client.second;
430
0
    reply[clientName] = this->BuildClientReply(clientQuery);
431
0
  }
432
433
  // Move our index of generated objects into its field.
434
0
  Json::Value& objects = index["objects"] = Json::arrayValue;
435
0
  for (auto& entry : this->ReplyIndexObjects) {
436
0
    objects.append(std::move(entry.second)); // NOLINT(*)
437
0
  }
438
439
0
  return index;
440
0
}
441
442
Json::Value cmFileAPI::BuildCMake()
443
0
{
444
0
  Json::Value cmake = Json::objectValue;
445
0
  cmake["version"] = this->CMakeInstance->ReportVersionJson();
446
0
  Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
447
0
  cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
448
0
  cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
449
0
  cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
450
0
  cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
451
0
  cmake["generator"] = this->CMakeInstance->GetGlobalGenerator()->GetJson();
452
0
  return cmake;
453
0
}
454
455
Json::Value cmFileAPI::BuildReply(Query const& q)
456
0
{
457
0
  Json::Value reply = Json::objectValue;
458
#ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
459
#  pragma clang diagnostic push
460
#  pragma clang diagnostic ignored "-Wrange-loop-analysis"
461
#endif
462
0
  for (Object const o : q.Known) {
463
#ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
464
#  pragma clang diagnostic pop
465
#endif
466
0
    std::string const& name = ObjectName(o);
467
0
    reply[name] = this->BuildReplyEntry(o);
468
0
  }
469
470
0
  for (std::string const& name : q.Unknown) {
471
0
    reply[name] = cmFileAPI::BuildReplyError("unknown query file");
472
0
  }
473
0
  return reply;
474
0
}
475
476
Json::Value cmFileAPI::BuildReplyEntry(Object object)
477
0
{
478
0
  if (this->ReplyIndexFor != IndexFor::Success) {
479
0
    switch (object.Kind) {
480
0
      case ObjectKind::ConfigureLog:
481
0
        break;
482
0
      case ObjectKind::CodeModel:
483
0
      case ObjectKind::Cache:
484
0
      case ObjectKind::CMakeFiles:
485
0
      case ObjectKind::Toolchains:
486
0
      case ObjectKind::InternalTest:
487
0
        return this->BuildReplyError("no buildsystem generated");
488
0
    }
489
0
  }
490
0
  return this->AddReplyIndexObject(object);
491
0
}
492
493
Json::Value cmFileAPI::BuildReplyError(std::string const& error)
494
0
{
495
0
  Json::Value e = Json::objectValue;
496
0
  e["error"] = error;
497
0
  return e;
498
0
}
499
500
Json::Value const& cmFileAPI::AddReplyIndexObject(Object o)
501
0
{
502
0
  Json::Value& indexEntry = this->ReplyIndexObjects[o];
503
0
  if (!indexEntry.isNull()) {
504
    // The reply object has already been generated.
505
0
    return indexEntry;
506
0
  }
507
508
  // Generate this reply object.
509
0
  Json::Value const& object = this->BuildObject(o);
510
0
  assert(object.isObject());
511
512
  // Populate this index entry.
513
0
  indexEntry = Json::objectValue;
514
0
  indexEntry["kind"] = object["kind"];
515
0
  indexEntry["version"] = object["version"];
516
0
  indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
517
0
  return indexEntry;
518
0
}
519
520
char const* cmFileAPI::ObjectKindName(ObjectKind kind)
521
0
{
522
  // Keep in sync with ObjectKind enum.
523
0
  static char const* objectKindNames[] = {
524
0
    "codemodel",    //
525
0
    "configureLog", //
526
0
    "cache",        //
527
0
    "cmakeFiles",   //
528
0
    "toolchains",   //
529
0
    "__test"        //
530
0
  };
531
0
  return objectKindNames[static_cast<size_t>(kind)];
532
0
}
533
534
std::string cmFileAPI::ObjectName(Object o)
535
0
{
536
0
  std::string name = cmStrCat(ObjectKindName(o.Kind), "-v", o.Version);
537
0
  return name;
538
0
}
539
540
Json::Value cmFileAPI::BuildVersion(unsigned int major, unsigned int minor)
541
0
{
542
0
  Json::Value version;
543
0
  version["major"] = major;
544
0
  version["minor"] = minor;
545
0
  return version;
546
0
}
547
548
Json::Value cmFileAPI::BuildObject(Object object)
549
0
{
550
0
  Json::Value value;
551
552
0
  switch (object.Kind) {
553
0
    case ObjectKind::CodeModel:
554
0
      value = this->BuildCodeModel(object);
555
0
      break;
556
0
    case ObjectKind::ConfigureLog:
557
0
      value = this->BuildConfigureLog(object);
558
0
      break;
559
0
    case ObjectKind::Cache:
560
0
      value = this->BuildCache(object);
561
0
      break;
562
0
    case ObjectKind::CMakeFiles:
563
0
      value = this->BuildCMakeFiles(object);
564
0
      break;
565
0
    case ObjectKind::Toolchains:
566
0
      value = this->BuildToolchains(object);
567
0
      break;
568
0
    case ObjectKind::InternalTest:
569
0
      value = this->BuildInternalTest(object);
570
0
      break;
571
0
  }
572
573
0
  return value;
574
0
}
575
576
cmFileAPI::ClientRequests cmFileAPI::BuildClientRequests(
577
  Json::Value const& requests)
578
0
{
579
0
  ClientRequests result;
580
0
  if (requests.isNull()) {
581
0
    result.Error = "'requests' member missing";
582
0
    return result;
583
0
  }
584
0
  if (!requests.isArray()) {
585
0
    result.Error = "'requests' member is not an array";
586
0
    return result;
587
0
  }
588
589
0
  result.reserve(requests.size());
590
0
  for (Json::Value const& request : requests) {
591
0
    result.emplace_back(this->BuildClientRequest(request));
592
0
  }
593
594
0
  return result;
595
0
}
596
597
cmFileAPI::ClientRequest cmFileAPI::BuildClientRequest(
598
  Json::Value const& request)
599
0
{
600
0
  ClientRequest r;
601
602
0
  if (!request.isObject()) {
603
0
    r.Error = "request is not an object";
604
0
    return r;
605
0
  }
606
607
0
  Json::Value const& kind = request["kind"];
608
0
  if (kind.isNull()) {
609
0
    r.Error = "'kind' member missing";
610
0
    return r;
611
0
  }
612
0
  if (!kind.isString()) {
613
0
    r.Error = "'kind' member is not a string";
614
0
    return r;
615
0
  }
616
0
  std::string const& kindName = kind.asString();
617
618
0
  if (kindName == this->ObjectKindName(ObjectKind::CodeModel)) {
619
0
    r.Kind = ObjectKind::CodeModel;
620
0
  } else if (kindName == this->ObjectKindName(ObjectKind::ConfigureLog)) {
621
0
    r.Kind = ObjectKind::ConfigureLog;
622
0
  } else if (kindName == this->ObjectKindName(ObjectKind::Cache)) {
623
0
    r.Kind = ObjectKind::Cache;
624
0
  } else if (kindName == this->ObjectKindName(ObjectKind::CMakeFiles)) {
625
0
    r.Kind = ObjectKind::CMakeFiles;
626
0
  } else if (kindName == this->ObjectKindName(ObjectKind::Toolchains)) {
627
0
    r.Kind = ObjectKind::Toolchains;
628
0
  } else if (kindName == this->ObjectKindName(ObjectKind::InternalTest)) {
629
0
    r.Kind = ObjectKind::InternalTest;
630
0
  } else {
631
0
    r.Error = cmStrCat("unknown request kind '", kindName, '\'');
632
0
    return r;
633
0
  }
634
635
0
  Json::Value const& version = request["version"];
636
0
  if (version.isNull()) {
637
0
    r.Error = "'version' member missing";
638
0
    return r;
639
0
  }
640
0
  std::vector<RequestVersion> versions;
641
0
  if (!cmFileAPI::ReadRequestVersions(version, versions, r.Error)) {
642
0
    return r;
643
0
  }
644
645
0
  switch (r.Kind) {
646
0
    case ObjectKind::CodeModel:
647
0
      this->BuildClientRequestCodeModel(r, versions);
648
0
      break;
649
0
    case ObjectKind::ConfigureLog:
650
0
      this->BuildClientRequestConfigureLog(r, versions);
651
0
      break;
652
0
    case ObjectKind::Cache:
653
0
      this->BuildClientRequestCache(r, versions);
654
0
      break;
655
0
    case ObjectKind::CMakeFiles:
656
0
      this->BuildClientRequestCMakeFiles(r, versions);
657
0
      break;
658
0
    case ObjectKind::Toolchains:
659
0
      this->BuildClientRequestToolchains(r, versions);
660
0
      break;
661
0
    case ObjectKind::InternalTest:
662
0
      this->BuildClientRequestInternalTest(r, versions);
663
0
      break;
664
0
  }
665
666
0
  return r;
667
0
}
668
669
Json::Value cmFileAPI::BuildClientReply(ClientQuery const& q)
670
0
{
671
0
  Json::Value reply = this->BuildReply(q.DirQuery);
672
673
0
  if (!q.HaveQueryJson) {
674
0
    return reply;
675
0
  }
676
677
0
  Json::Value& reply_query_json = reply["query.json"];
678
0
  ClientQueryJson const& qj = q.QueryJson;
679
680
0
  if (!qj.Error.empty()) {
681
0
    reply_query_json = this->BuildReplyError(qj.Error);
682
0
    return reply;
683
0
  }
684
685
0
  if (!qj.ClientValue.isNull()) {
686
0
    reply_query_json["client"] = qj.ClientValue;
687
0
  }
688
689
0
  if (!qj.RequestsValue.isNull()) {
690
0
    reply_query_json["requests"] = qj.RequestsValue;
691
0
  }
692
693
0
  reply_query_json["responses"] = this->BuildClientReplyResponses(qj.Requests);
694
695
0
  return reply;
696
0
}
697
698
Json::Value cmFileAPI::BuildClientReplyResponses(
699
  ClientRequests const& requests)
700
0
{
701
0
  Json::Value responses;
702
703
0
  if (!requests.Error.empty()) {
704
0
    responses = this->BuildReplyError(requests.Error);
705
0
    return responses;
706
0
  }
707
708
0
  responses = Json::arrayValue;
709
0
  for (ClientRequest const& request : requests) {
710
0
    responses.append(this->BuildClientReplyResponse(request));
711
0
  }
712
713
0
  return responses;
714
0
}
715
716
Json::Value cmFileAPI::BuildClientReplyResponse(ClientRequest const& request)
717
0
{
718
0
  Json::Value response;
719
0
  if (!request.Error.empty()) {
720
0
    response = this->BuildReplyError(request.Error);
721
0
    return response;
722
0
  }
723
0
  response = this->BuildReplyEntry(request);
724
0
  return response;
725
0
}
726
727
bool cmFileAPI::ReadRequestVersions(Json::Value const& version,
728
                                    std::vector<RequestVersion>& versions,
729
                                    std::string& error)
730
0
{
731
0
  if (version.isArray()) {
732
0
    for (Json::Value const& v : version) {
733
0
      if (!ReadRequestVersion(v, /*inArray=*/true, versions, error)) {
734
0
        return false;
735
0
      }
736
0
    }
737
0
  } else {
738
0
    if (!ReadRequestVersion(version, /*inArray=*/false, versions, error)) {
739
0
      return false;
740
0
    }
741
0
  }
742
0
  return true;
743
0
}
744
745
bool cmFileAPI::ReadRequestVersion(Json::Value const& version, bool inArray,
746
                                   std::vector<RequestVersion>& result,
747
                                   std::string& error)
748
0
{
749
0
  if (version.isUInt()) {
750
0
    RequestVersion v;
751
0
    v.Major = version.asUInt();
752
0
    result.push_back(v);
753
0
    return true;
754
0
  }
755
756
0
  if (!version.isObject()) {
757
0
    if (inArray) {
758
0
      error = "'version' array entry is not a non-negative integer or object";
759
0
    } else {
760
0
      error =
761
0
        "'version' member is not a non-negative integer, object, or array";
762
0
    }
763
0
    return false;
764
0
  }
765
766
0
  Json::Value const& major = version["major"];
767
0
  if (major.isNull()) {
768
0
    error = "'version' object 'major' member missing";
769
0
    return false;
770
0
  }
771
0
  if (!major.isUInt()) {
772
0
    error = "'version' object 'major' member is not a non-negative integer";
773
0
    return false;
774
0
  }
775
776
0
  RequestVersion v;
777
0
  v.Major = major.asUInt();
778
779
0
  Json::Value const& minor = version["minor"];
780
0
  if (minor.isUInt()) {
781
0
    v.Minor = minor.asUInt();
782
0
  } else if (!minor.isNull()) {
783
0
    error = "'version' object 'minor' member is not a non-negative integer";
784
0
    return false;
785
0
  }
786
787
0
  result.push_back(v);
788
789
0
  return true;
790
0
}
791
792
std::string cmFileAPI::NoSupportedVersion(
793
  std::vector<RequestVersion> const& versions)
794
0
{
795
0
  std::ostringstream msg;
796
0
  msg << "no supported version specified";
797
0
  if (!versions.empty()) {
798
0
    msg << " among:";
799
0
    for (RequestVersion const& v : versions) {
800
0
      msg << " " << v.Major << "." << v.Minor;
801
0
    }
802
0
  }
803
0
  return msg.str();
804
0
}
805
806
// The "codemodel" object kind.
807
808
// Update the following files as well when updating this constant:
809
//   Help/manual/cmake-file-api.7.rst
810
//   Tests/RunCMake/FileAPI/codemodel-v2-check.py (check_objects())
811
static unsigned int const CodeModelV2Minor = 12;
812
813
void cmFileAPI::BuildClientRequestCodeModel(
814
  ClientRequest& r, std::vector<RequestVersion> const& versions)
815
0
{
816
  // Select a known version from those requested.
817
0
  for (RequestVersion const& v : versions) {
818
0
    if ((v.Major == 2 && v.Minor <= CodeModelV2Minor)) {
819
0
      r.Version = v.Major;
820
0
      break;
821
0
    }
822
0
  }
823
0
  if (!r.Version) {
824
0
    r.Error = NoSupportedVersion(versions);
825
0
  }
826
0
}
827
828
Json::Value cmFileAPI::BuildCodeModel(Object object)
829
0
{
830
0
  assert(object.Version == 2);
831
0
  Json::Value codemodel =
832
0
    cmFileAPICodemodelDump(*this, object.Version, CodeModelV2Minor);
833
0
  codemodel["kind"] = this->ObjectKindName(object.Kind);
834
835
0
  Json::Value& version = codemodel["version"];
836
0
  if (object.Version == 2) {
837
0
    version = BuildVersion(2, CodeModelV2Minor);
838
0
  } else {
839
0
    CM_UNREACHABLE;
840
0
  }
841
842
0
  return codemodel;
843
0
}
844
845
// The "configureLog" object kind.
846
847
// Update Help/manual/cmake-file-api.7.rst when updating this constant.
848
static unsigned int const ConfigureLogV1Minor = 0;
849
850
void cmFileAPI::BuildClientRequestConfigureLog(
851
  ClientRequest& r, std::vector<RequestVersion> const& versions)
852
0
{
853
  // Select a known version from those requested.
854
0
  for (RequestVersion const& v : versions) {
855
0
    if ((v.Major == 1 && v.Minor <= ConfigureLogV1Minor)) {
856
0
      r.Version = v.Major;
857
0
      break;
858
0
    }
859
0
  }
860
0
  if (!r.Version) {
861
0
    r.Error = NoSupportedVersion(versions);
862
0
  }
863
0
}
864
865
Json::Value cmFileAPI::BuildConfigureLog(Object object)
866
0
{
867
0
  Json::Value configureLog = cmFileAPIConfigureLogDump(*this, object.Version);
868
0
  configureLog["kind"] = this->ObjectKindName(object.Kind);
869
870
0
  Json::Value& version = configureLog["version"];
871
0
  if (object.Version == 1) {
872
0
    version = BuildVersion(1, ConfigureLogV1Minor);
873
0
  } else {
874
0
    CM_UNREACHABLE;
875
0
  }
876
877
0
  return configureLog;
878
0
}
879
880
// The "cache" object kind.
881
882
static unsigned int const CacheV2Minor = 0;
883
884
void cmFileAPI::BuildClientRequestCache(
885
  ClientRequest& r, std::vector<RequestVersion> const& versions)
886
0
{
887
  // Select a known version from those requested.
888
0
  for (RequestVersion const& v : versions) {
889
0
    if ((v.Major == 2 && v.Minor <= CacheV2Minor)) {
890
0
      r.Version = v.Major;
891
0
      break;
892
0
    }
893
0
  }
894
0
  if (!r.Version) {
895
0
    r.Error = NoSupportedVersion(versions);
896
0
  }
897
0
}
898
899
Json::Value cmFileAPI::BuildCache(Object object)
900
0
{
901
0
  Json::Value cache = cmFileAPICacheDump(*this, object.Version);
902
0
  cache["kind"] = this->ObjectKindName(object.Kind);
903
904
0
  Json::Value& version = cache["version"];
905
0
  if (object.Version == 2) {
906
0
    version = BuildVersion(2, CacheV2Minor);
907
0
  } else {
908
0
    CM_UNREACHABLE;
909
0
  }
910
911
0
  return cache;
912
0
}
913
914
// The "cmakeFiles" object kind.
915
916
static unsigned int const CMakeFilesV1Minor = 1;
917
918
void cmFileAPI::BuildClientRequestCMakeFiles(
919
  ClientRequest& r, std::vector<RequestVersion> const& versions)
920
0
{
921
  // Select a known version from those requested.
922
0
  for (RequestVersion const& v : versions) {
923
0
    if ((v.Major == 1 && v.Minor <= CMakeFilesV1Minor)) {
924
0
      r.Version = v.Major;
925
0
      break;
926
0
    }
927
0
  }
928
0
  if (!r.Version) {
929
0
    r.Error = NoSupportedVersion(versions);
930
0
  }
931
0
}
932
933
Json::Value cmFileAPI::BuildCMakeFiles(Object object)
934
0
{
935
0
  Json::Value cmakeFiles = cmFileAPICMakeFilesDump(*this, object.Version);
936
0
  cmakeFiles["kind"] = this->ObjectKindName(object.Kind);
937
938
0
  Json::Value& version = cmakeFiles["version"];
939
0
  if (object.Version == 1) {
940
0
    version = BuildVersion(1, CMakeFilesV1Minor);
941
0
  } else {
942
0
    CM_UNREACHABLE;
943
0
  }
944
945
0
  return cmakeFiles;
946
0
}
947
948
// The "toolchains" object kind.
949
950
static unsigned int const ToolchainsV1Minor = 1;
951
952
void cmFileAPI::BuildClientRequestToolchains(
953
  ClientRequest& r, std::vector<RequestVersion> const& versions)
954
0
{
955
  // Select a known version from those requested.
956
0
  for (RequestVersion const& v : versions) {
957
0
    if ((v.Major == 1 && v.Minor <= ToolchainsV1Minor)) {
958
0
      r.Version = v.Major;
959
0
      break;
960
0
    }
961
0
  }
962
0
  if (!r.Version) {
963
0
    r.Error = NoSupportedVersion(versions);
964
0
  }
965
0
}
966
967
Json::Value cmFileAPI::BuildToolchains(Object object)
968
0
{
969
0
  Json::Value toolchains = cmFileAPIToolchainsDump(*this, object.Version);
970
0
  toolchains["kind"] = this->ObjectKindName(object.Kind);
971
972
0
  Json::Value& version = toolchains["version"];
973
0
  if (object.Version == 1) {
974
0
    version = BuildVersion(1, ToolchainsV1Minor);
975
0
  } else {
976
0
    CM_UNREACHABLE;
977
0
  }
978
979
0
  return toolchains;
980
0
}
981
982
// The "__test" object kind is for internal testing of CMake.
983
984
static unsigned int const InternalTestV1Minor = 3;
985
static unsigned int const InternalTestV2Minor = 0;
986
987
void cmFileAPI::BuildClientRequestInternalTest(
988
  ClientRequest& r, std::vector<RequestVersion> const& versions)
989
0
{
990
  // Select a known version from those requested.
991
0
  for (RequestVersion const& v : versions) {
992
0
    if ((v.Major == 1 && v.Minor <= InternalTestV1Minor) || //
993
0
        (v.Major == 2 && v.Minor <= InternalTestV2Minor)) {
994
0
      r.Version = v.Major;
995
0
      break;
996
0
    }
997
0
  }
998
0
  if (!r.Version) {
999
0
    r.Error = NoSupportedVersion(versions);
1000
0
  }
1001
0
}
1002
1003
Json::Value cmFileAPI::BuildInternalTest(Object object)
1004
0
{
1005
0
  Json::Value test = Json::objectValue;
1006
0
  test["kind"] = this->ObjectKindName(object.Kind);
1007
0
  Json::Value& version = test["version"];
1008
0
  if (object.Version == 2) {
1009
0
    version = BuildVersion(2, InternalTestV2Minor);
1010
0
  } else {
1011
0
    version = BuildVersion(1, InternalTestV1Minor);
1012
0
  }
1013
0
  return test;
1014
0
}
1015
1016
Json::Value cmFileAPI::ReportCapabilities()
1017
0
{
1018
0
  Json::Value capabilities = Json::objectValue;
1019
0
  Json::Value& requests = capabilities["requests"] = Json::arrayValue;
1020
1021
0
  {
1022
0
    Json::Value request = Json::objectValue;
1023
0
    request["kind"] = ObjectKindName(ObjectKind::CodeModel);
1024
0
    Json::Value& versions = request["version"] = Json::arrayValue;
1025
0
    versions.append(BuildVersion(2, CodeModelV2Minor));
1026
0
    requests.append(std::move(request)); // NOLINT(*)
1027
0
  }
1028
1029
0
  {
1030
0
    Json::Value request = Json::objectValue;
1031
0
    request["kind"] = ObjectKindName(ObjectKind::ConfigureLog);
1032
0
    Json::Value& versions = request["version"] = Json::arrayValue;
1033
0
    versions.append(BuildVersion(1, ConfigureLogV1Minor));
1034
0
    requests.append(std::move(request)); // NOLINT(*)
1035
0
  }
1036
1037
0
  {
1038
0
    Json::Value request = Json::objectValue;
1039
0
    request["kind"] = ObjectKindName(ObjectKind::Cache);
1040
0
    Json::Value& versions = request["version"] = Json::arrayValue;
1041
0
    versions.append(BuildVersion(2, CacheV2Minor));
1042
0
    requests.append(std::move(request)); // NOLINT(*)
1043
0
  }
1044
1045
0
  {
1046
0
    Json::Value request = Json::objectValue;
1047
0
    request["kind"] = ObjectKindName(ObjectKind::CMakeFiles);
1048
0
    Json::Value& versions = request["version"] = Json::arrayValue;
1049
0
    versions.append(BuildVersion(1, CMakeFilesV1Minor));
1050
0
    requests.append(std::move(request)); // NOLINT(*)
1051
0
  }
1052
1053
0
  {
1054
0
    Json::Value request = Json::objectValue;
1055
0
    request["kind"] = ObjectKindName(ObjectKind::Toolchains);
1056
0
    Json::Value& versions = request["version"] = Json::arrayValue;
1057
0
    versions.append(BuildVersion(1, ToolchainsV1Minor));
1058
0
    requests.append(std::move(request)); // NOLINT(*)
1059
0
  }
1060
1061
0
  return capabilities;
1062
0
}
1063
1064
bool cmFileAPI::AddProjectQuery(cmFileAPI::ObjectKind kind,
1065
                                unsigned majorVersion, unsigned minorVersion)
1066
0
{
1067
0
  switch (kind) {
1068
0
    case ObjectKind::CodeModel:
1069
0
      if (majorVersion != 2 || minorVersion > CodeModelV2Minor) {
1070
0
        return false;
1071
0
      }
1072
0
      break;
1073
0
    case ObjectKind::Cache:
1074
0
      if (majorVersion != 2 || minorVersion > CacheV2Minor) {
1075
0
        return false;
1076
0
      }
1077
0
      break;
1078
0
    case ObjectKind::CMakeFiles:
1079
0
      if (majorVersion != 1 || minorVersion > CMakeFilesV1Minor) {
1080
0
        return false;
1081
0
      }
1082
0
      break;
1083
0
    case ObjectKind::Toolchains:
1084
0
      if (majorVersion != 1 || minorVersion > ToolchainsV1Minor) {
1085
0
        return false;
1086
0
      }
1087
0
      break;
1088
    // These cannot be requested by the project
1089
0
    case ObjectKind::ConfigureLog:
1090
0
    case ObjectKind::InternalTest:
1091
0
      return false;
1092
0
  }
1093
1094
0
  Object query;
1095
0
  query.Kind = kind;
1096
0
  query.Version = majorVersion;
1097
0
  if (std::find(this->TopQuery.Known.begin(), this->TopQuery.Known.end(),
1098
0
                query) == this->TopQuery.Known.end()) {
1099
0
    this->TopQuery.Known.emplace_back(query);
1100
0
    this->QueryExists = true;
1101
0
  }
1102
1103
0
  return true;
1104
0
}