cmServerProtocol.cxx 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmServerProtocol.h"
  4. #include "cmExternalMakefileProjectGenerator.h"
  5. #include "cmFileMonitor.h"
  6. #include "cmGeneratorExpression.h"
  7. #include "cmGeneratorTarget.h"
  8. #include "cmGlobalGenerator.h"
  9. #include "cmLinkLineComputer.h"
  10. #include "cmLocalGenerator.h"
  11. #include "cmMakefile.h"
  12. #include "cmServer.h"
  13. #include "cmServerDictionary.h"
  14. #include "cmSourceFile.h"
  15. #include "cmState.h"
  16. #include "cmStateDirectory.h"
  17. #include "cmStateSnapshot.h"
  18. #include "cmStateTypes.h"
  19. #include "cmSystemTools.h"
  20. #include "cm_uv.h"
  21. #include "cmake.h"
  22. #include <algorithm>
  23. #include <cassert>
  24. #include <cstddef>
  25. #include <functional>
  26. #include <limits>
  27. #include <map>
  28. #include <set>
  29. #include <string>
  30. #include <unordered_map>
  31. #include <vector>
  32. // Get rid of some windows macros:
  33. #undef max
  34. namespace {
  35. std::vector<std::string> getConfigurations(const cmake* cm)
  36. {
  37. std::vector<std::string> configurations;
  38. auto makefiles = cm->GetGlobalGenerator()->GetMakefiles();
  39. if (makefiles.empty()) {
  40. return configurations;
  41. }
  42. makefiles[0]->GetConfigurations(configurations);
  43. if (configurations.empty()) {
  44. configurations.push_back("");
  45. }
  46. return configurations;
  47. }
  48. bool hasString(const Json::Value& v, const std::string& s)
  49. {
  50. return !v.isNull() &&
  51. std::any_of(v.begin(), v.end(),
  52. [s](const Json::Value& i) { return i.asString() == s; });
  53. }
  54. template <class T>
  55. Json::Value fromStringList(const T& in)
  56. {
  57. Json::Value result = Json::arrayValue;
  58. for (const std::string& i : in) {
  59. result.append(i);
  60. }
  61. return result;
  62. }
  63. std::vector<std::string> toStringList(const Json::Value& in)
  64. {
  65. std::vector<std::string> result;
  66. for (const auto& it : in) {
  67. result.push_back(it.asString());
  68. }
  69. return result;
  70. }
  71. void getCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir,
  72. const std::string& buildDir,
  73. std::vector<std::string>* internalFiles,
  74. std::vector<std::string>* explicitFiles,
  75. std::vector<std::string>* tmpFiles)
  76. {
  77. const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/';
  78. std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles();
  79. for (auto it = makefiles.begin(); it != makefiles.end(); ++it) {
  80. const std::vector<std::string> listFiles = (*it)->GetListFiles();
  81. for (auto jt = listFiles.begin(); jt != listFiles.end(); ++jt) {
  82. const std::string startOfFile = jt->substr(0, cmakeRootDir.size());
  83. const bool isInternal = (startOfFile == cmakeRootDir);
  84. const bool isTemporary = !isInternal && (jt->find(buildDir + '/') == 0);
  85. std::string toAdd = *jt;
  86. if (!sourceDir.empty()) {
  87. const std::string& relative =
  88. cmSystemTools::RelativePath(sourceDir.c_str(), jt->c_str());
  89. if (toAdd.size() > relative.size()) {
  90. toAdd = relative;
  91. }
  92. }
  93. if (isInternal) {
  94. if (internalFiles) {
  95. internalFiles->push_back(toAdd);
  96. }
  97. } else {
  98. if (isTemporary) {
  99. if (tmpFiles) {
  100. tmpFiles->push_back(toAdd);
  101. }
  102. } else {
  103. if (explicitFiles) {
  104. explicitFiles->push_back(toAdd);
  105. }
  106. }
  107. }
  108. }
  109. }
  110. }
  111. } // namespace
  112. cmServerRequest::cmServerRequest(cmServer* server, const std::string& t,
  113. const std::string& c, const Json::Value& d)
  114. : Type(t)
  115. , Cookie(c)
  116. , Data(d)
  117. , m_Server(server)
  118. {
  119. }
  120. void cmServerRequest::ReportProgress(int min, int current, int max,
  121. const std::string& message) const
  122. {
  123. this->m_Server->WriteProgress(*this, min, current, max, message);
  124. }
  125. void cmServerRequest::ReportMessage(const std::string& message,
  126. const std::string& title) const
  127. {
  128. m_Server->WriteMessage(*this, message, title);
  129. }
  130. cmServerResponse cmServerRequest::Reply(const Json::Value& data) const
  131. {
  132. cmServerResponse response(*this);
  133. response.SetData(data);
  134. return response;
  135. }
  136. cmServerResponse cmServerRequest::ReportError(const std::string& message) const
  137. {
  138. cmServerResponse response(*this);
  139. response.SetError(message);
  140. return response;
  141. }
  142. cmServerResponse::cmServerResponse(const cmServerRequest& request)
  143. : Type(request.Type)
  144. , Cookie(request.Cookie)
  145. {
  146. }
  147. void cmServerResponse::SetData(const Json::Value& data)
  148. {
  149. assert(this->m_Payload == PAYLOAD_UNKNOWN);
  150. if (!data[kCOOKIE_KEY].isNull() || !data[kTYPE_KEY].isNull()) {
  151. this->SetError("Response contains cookie or type field.");
  152. return;
  153. }
  154. this->m_Payload = PAYLOAD_DATA;
  155. this->m_Data = data;
  156. }
  157. void cmServerResponse::SetError(const std::string& message)
  158. {
  159. assert(this->m_Payload == PAYLOAD_UNKNOWN);
  160. this->m_Payload = PAYLOAD_ERROR;
  161. this->m_ErrorMessage = message;
  162. }
  163. bool cmServerResponse::IsComplete() const
  164. {
  165. return this->m_Payload != PAYLOAD_UNKNOWN;
  166. }
  167. bool cmServerResponse::IsError() const
  168. {
  169. assert(this->m_Payload != PAYLOAD_UNKNOWN);
  170. return this->m_Payload == PAYLOAD_ERROR;
  171. }
  172. std::string cmServerResponse::ErrorMessage() const
  173. {
  174. if (this->m_Payload == PAYLOAD_ERROR) {
  175. return this->m_ErrorMessage;
  176. }
  177. return std::string();
  178. }
  179. Json::Value cmServerResponse::Data() const
  180. {
  181. assert(this->m_Payload != PAYLOAD_UNKNOWN);
  182. return this->m_Data;
  183. }
  184. bool cmServerProtocol::Activate(cmServer* server,
  185. const cmServerRequest& request,
  186. std::string* errorMessage)
  187. {
  188. assert(server);
  189. this->m_Server = server;
  190. this->m_CMakeInstance = std::make_unique<cmake>(cmake::RoleProject);
  191. const bool result = this->DoActivate(request, errorMessage);
  192. if (!result) {
  193. this->m_CMakeInstance = CM_NULLPTR;
  194. }
  195. return result;
  196. }
  197. cmFileMonitor* cmServerProtocol::FileMonitor() const
  198. {
  199. return this->m_Server ? this->m_Server->FileMonitor() : nullptr;
  200. }
  201. void cmServerProtocol::SendSignal(const std::string& name,
  202. const Json::Value& data) const
  203. {
  204. if (this->m_Server) {
  205. this->m_Server->WriteSignal(name, data);
  206. }
  207. }
  208. cmake* cmServerProtocol::CMakeInstance() const
  209. {
  210. return this->m_CMakeInstance.get();
  211. }
  212. bool cmServerProtocol::DoActivate(const cmServerRequest& /*request*/,
  213. std::string* /*errorMessage*/)
  214. {
  215. return true;
  216. }
  217. std::pair<int, int> cmServerProtocol1::ProtocolVersion() const
  218. {
  219. return std::make_pair(1, 0);
  220. }
  221. static void setErrorMessage(std::string* errorMessage, const std::string& text)
  222. {
  223. if (errorMessage) {
  224. *errorMessage = text;
  225. }
  226. }
  227. static bool testHomeDirectory(cmState* state, std::string& value,
  228. std::string* errorMessage)
  229. {
  230. const std::string cachedValue =
  231. std::string(state->GetCacheEntryValue("CMAKE_HOME_DIRECTORY"));
  232. const std::string suffix = "/CMakeLists.txt";
  233. const std::string cachedValueCML = cachedValue + suffix;
  234. const std::string valueCML = value + suffix;
  235. if (!cmSystemTools::SameFile(valueCML, cachedValueCML)) {
  236. setErrorMessage(errorMessage,
  237. std::string("\"CMAKE_HOME_DIRECTORY\" is set but "
  238. "incompatible with configured "
  239. "source directory value."));
  240. return false;
  241. }
  242. if (value.empty()) {
  243. value = cachedValue;
  244. }
  245. return true;
  246. }
  247. static bool testValue(cmState* state, const std::string& key,
  248. std::string& value, const std::string& keyDescription,
  249. std::string* errorMessage)
  250. {
  251. const std::string cachedValue = std::string(state->GetCacheEntryValue(key));
  252. if (!cachedValue.empty() && !value.empty() && cachedValue != value) {
  253. setErrorMessage(errorMessage, std::string("\"") + key +
  254. "\" is set but incompatible with configured " +
  255. keyDescription + " value.");
  256. return false;
  257. }
  258. if (value.empty()) {
  259. value = cachedValue;
  260. }
  261. return true;
  262. }
  263. bool cmServerProtocol1::DoActivate(const cmServerRequest& request,
  264. std::string* errorMessage)
  265. {
  266. std::string sourceDirectory = request.Data[kSOURCE_DIRECTORY_KEY].asString();
  267. const std::string buildDirectory =
  268. request.Data[kBUILD_DIRECTORY_KEY].asString();
  269. std::string generator = request.Data[kGENERATOR_KEY].asString();
  270. std::string extraGenerator = request.Data[kEXTRA_GENERATOR_KEY].asString();
  271. std::string toolset = request.Data[kTOOLSET_KEY].asString();
  272. std::string platform = request.Data[kPLATFORM_KEY].asString();
  273. if (buildDirectory.empty()) {
  274. setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY +
  275. "\" is missing.");
  276. return false;
  277. }
  278. cmake* cm = CMakeInstance();
  279. if (cmSystemTools::PathExists(buildDirectory)) {
  280. if (!cmSystemTools::FileIsDirectory(buildDirectory)) {
  281. setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY +
  282. "\" exists but is not a directory.");
  283. return false;
  284. }
  285. const std::string cachePath = cm->FindCacheFile(buildDirectory);
  286. if (cm->LoadCache(cachePath)) {
  287. cmState* state = cm->GetState();
  288. // Check generator:
  289. if (!testValue(state, "CMAKE_GENERATOR", generator, "generator",
  290. errorMessage)) {
  291. return false;
  292. }
  293. // check extra generator:
  294. if (!testValue(state, "CMAKE_EXTRA_GENERATOR", extraGenerator,
  295. "extra generator", errorMessage)) {
  296. return false;
  297. }
  298. // check sourcedir:
  299. if (!testHomeDirectory(state, sourceDirectory, errorMessage)) {
  300. return false;
  301. }
  302. // check toolset:
  303. if (!testValue(state, "CMAKE_GENERATOR_TOOLSET", toolset, "toolset",
  304. errorMessage)) {
  305. return false;
  306. }
  307. // check platform:
  308. if (!testValue(state, "CMAKE_GENERATOR_PLATFORM", platform, "platform",
  309. errorMessage)) {
  310. return false;
  311. }
  312. }
  313. }
  314. if (sourceDirectory.empty()) {
  315. setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY +
  316. "\" is unset but required.");
  317. return false;
  318. }
  319. if (!cmSystemTools::FileIsDirectory(sourceDirectory)) {
  320. setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY +
  321. "\" is not a directory.");
  322. return false;
  323. }
  324. if (generator.empty()) {
  325. setErrorMessage(errorMessage, std::string("\"") + kGENERATOR_KEY +
  326. "\" is unset but required.");
  327. return false;
  328. }
  329. std::vector<cmake::GeneratorInfo> generators;
  330. cm->GetRegisteredGenerators(generators);
  331. auto baseIt = std::find_if(generators.begin(), generators.end(),
  332. [&generator](const cmake::GeneratorInfo& info) {
  333. return info.name == generator;
  334. });
  335. if (baseIt == generators.end()) {
  336. setErrorMessage(errorMessage, std::string("Generator \"") + generator +
  337. "\" not supported.");
  338. return false;
  339. }
  340. auto extraIt = std::find_if(
  341. generators.begin(), generators.end(),
  342. [&generator, &extraGenerator](const cmake::GeneratorInfo& info) {
  343. return info.baseName == generator && info.extraName == extraGenerator;
  344. });
  345. if (extraIt == generators.end()) {
  346. setErrorMessage(errorMessage,
  347. std::string("The combination of generator \"" + generator +
  348. "\" and extra generator \"" + extraGenerator +
  349. "\" is not supported."));
  350. return false;
  351. }
  352. if (!extraIt->supportsToolset && !toolset.empty()) {
  353. setErrorMessage(errorMessage,
  354. std::string("Toolset was provided but is not supported by "
  355. "the requested generator."));
  356. return false;
  357. }
  358. if (!extraIt->supportsPlatform && !platform.empty()) {
  359. setErrorMessage(errorMessage,
  360. std::string("Platform was provided but is not supported "
  361. "by the requested generator."));
  362. return false;
  363. }
  364. this->GeneratorInfo =
  365. GeneratorInformation(generator, extraGenerator, toolset, platform,
  366. sourceDirectory, buildDirectory);
  367. this->m_State = STATE_ACTIVE;
  368. return true;
  369. }
  370. void cmServerProtocol1::HandleCMakeFileChanges(const std::string& path,
  371. int event, int status)
  372. {
  373. assert(status == 0);
  374. static_cast<void>(status);
  375. if (!m_isDirty) {
  376. m_isDirty = true;
  377. SendSignal(kDIRTY_SIGNAL, Json::objectValue);
  378. }
  379. Json::Value obj = Json::objectValue;
  380. obj[kPATH_KEY] = path;
  381. Json::Value properties = Json::arrayValue;
  382. if (event & UV_RENAME) {
  383. properties.append(kRENAME_PROPERTY_VALUE);
  384. }
  385. if (event & UV_CHANGE) {
  386. properties.append(kCHANGE_PROPERTY_VALUE);
  387. }
  388. obj[kPROPERTIES_KEY] = properties;
  389. SendSignal(kFILE_CHANGE_SIGNAL, obj);
  390. }
  391. const cmServerResponse cmServerProtocol1::Process(
  392. const cmServerRequest& request)
  393. {
  394. assert(this->m_State >= STATE_ACTIVE);
  395. if (request.Type == kCACHE_TYPE) {
  396. return this->ProcessCache(request);
  397. }
  398. if (request.Type == kCMAKE_INPUTS_TYPE) {
  399. return this->ProcessCMakeInputs(request);
  400. }
  401. if (request.Type == kCODE_MODEL_TYPE) {
  402. return this->ProcessCodeModel(request);
  403. }
  404. if (request.Type == kCOMPUTE_TYPE) {
  405. return this->ProcessCompute(request);
  406. }
  407. if (request.Type == kCONFIGURE_TYPE) {
  408. return this->ProcessConfigure(request);
  409. }
  410. if (request.Type == kFILESYSTEM_WATCHERS_TYPE) {
  411. return this->ProcessFileSystemWatchers(request);
  412. }
  413. if (request.Type == kGLOBAL_SETTINGS_TYPE) {
  414. return this->ProcessGlobalSettings(request);
  415. }
  416. if (request.Type == kSET_GLOBAL_SETTINGS_TYPE) {
  417. return this->ProcessSetGlobalSettings(request);
  418. }
  419. return request.ReportError("Unknown command!");
  420. }
  421. bool cmServerProtocol1::IsExperimental() const
  422. {
  423. return true;
  424. }
  425. cmServerResponse cmServerProtocol1::ProcessCache(
  426. const cmServerRequest& request)
  427. {
  428. if (this->m_State < STATE_CONFIGURED) {
  429. return request.ReportError("This project was not configured yet.");
  430. }
  431. cmState* state = this->CMakeInstance()->GetState();
  432. Json::Value result = Json::objectValue;
  433. std::vector<std::string> allKeys = state->GetCacheEntryKeys();
  434. Json::Value list = Json::arrayValue;
  435. std::vector<std::string> keys = toStringList(request.Data[kKEYS_KEY]);
  436. if (keys.empty()) {
  437. keys = allKeys;
  438. } else {
  439. for (const auto& i : keys) {
  440. if (std::find(allKeys.begin(), allKeys.end(), i) == allKeys.end()) {
  441. return request.ReportError("Key \"" + i + "\" not found in cache.");
  442. }
  443. }
  444. }
  445. std::sort(keys.begin(), keys.end());
  446. for (const auto& key : keys) {
  447. Json::Value entry = Json::objectValue;
  448. entry[kKEY_KEY] = key;
  449. entry[kTYPE_KEY] =
  450. cmState::CacheEntryTypeToString(state->GetCacheEntryType(key));
  451. entry[kVALUE_KEY] = state->GetCacheEntryValue(key);
  452. Json::Value props = Json::objectValue;
  453. bool haveProperties = false;
  454. for (const auto& prop : state->GetCacheEntryPropertyList(key)) {
  455. haveProperties = true;
  456. props[prop] = state->GetCacheEntryProperty(key, prop);
  457. }
  458. if (haveProperties) {
  459. entry[kPROPERTIES_KEY] = props;
  460. }
  461. list.append(entry);
  462. }
  463. result[kCACHE_KEY] = list;
  464. return request.Reply(result);
  465. }
  466. cmServerResponse cmServerProtocol1::ProcessCMakeInputs(
  467. const cmServerRequest& request)
  468. {
  469. if (this->m_State < STATE_CONFIGURED) {
  470. return request.ReportError("This instance was not yet configured.");
  471. }
  472. const cmake* cm = this->CMakeInstance();
  473. const cmGlobalGenerator* gg = cm->GetGlobalGenerator();
  474. const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot();
  475. const std::string buildDir = cm->GetHomeOutputDirectory();
  476. const std::string sourceDir = cm->GetHomeDirectory();
  477. Json::Value result = Json::objectValue;
  478. result[kSOURCE_DIRECTORY_KEY] = sourceDir;
  479. result[kCMAKE_ROOT_DIRECTORY_KEY] = cmakeRootDir;
  480. std::vector<std::string> internalFiles;
  481. std::vector<std::string> explicitFiles;
  482. std::vector<std::string> tmpFiles;
  483. getCMakeInputs(gg, sourceDir, buildDir, &internalFiles, &explicitFiles,
  484. &tmpFiles);
  485. Json::Value array = Json::arrayValue;
  486. Json::Value tmp = Json::objectValue;
  487. tmp[kIS_CMAKE_KEY] = true;
  488. tmp[kIS_TEMPORARY_KEY] = false;
  489. tmp[kSOURCES_KEY] = fromStringList(internalFiles);
  490. array.append(tmp);
  491. tmp = Json::objectValue;
  492. tmp[kIS_CMAKE_KEY] = false;
  493. tmp[kIS_TEMPORARY_KEY] = false;
  494. tmp[kSOURCES_KEY] = fromStringList(explicitFiles);
  495. array.append(tmp);
  496. tmp = Json::objectValue;
  497. tmp[kIS_CMAKE_KEY] = false;
  498. tmp[kIS_TEMPORARY_KEY] = true;
  499. tmp[kSOURCES_KEY] = fromStringList(tmpFiles);
  500. array.append(tmp);
  501. result[kBUILD_FILES_KEY] = array;
  502. return request.Reply(result);
  503. }
  504. class LanguageData
  505. {
  506. public:
  507. bool operator==(const LanguageData& other) const;
  508. void SetDefines(const std::set<std::string>& defines);
  509. bool IsGenerated = false;
  510. std::string Language;
  511. std::string Flags;
  512. std::vector<std::string> Defines;
  513. std::vector<std::pair<std::string, bool> > IncludePathList;
  514. };
  515. bool LanguageData::operator==(const LanguageData& other) const
  516. {
  517. return Language == other.Language && Defines == other.Defines &&
  518. Flags == other.Flags && IncludePathList == other.IncludePathList &&
  519. IsGenerated == other.IsGenerated;
  520. }
  521. void LanguageData::SetDefines(const std::set<std::string>& defines)
  522. {
  523. std::vector<std::string> result;
  524. for (const auto& i : defines) {
  525. result.push_back(i);
  526. }
  527. std::sort(result.begin(), result.end());
  528. Defines = result;
  529. }
  530. namespace std {
  531. template <>
  532. struct hash<LanguageData>
  533. {
  534. std::size_t operator()(const LanguageData& in) const
  535. {
  536. using std::hash;
  537. size_t result =
  538. hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags);
  539. for (const auto& i : in.IncludePathList) {
  540. result = result ^ (hash<std::string>()(i.first) ^
  541. (i.second ? std::numeric_limits<size_t>::max() : 0));
  542. }
  543. for (const auto& i : in.Defines) {
  544. result = result ^ hash<std::string>()(i);
  545. }
  546. result =
  547. result ^ (in.IsGenerated ? std::numeric_limits<size_t>::max() : 0);
  548. return result;
  549. }
  550. };
  551. } // namespace std
  552. static Json::Value DumpSourceFileGroup(const LanguageData& data,
  553. const std::vector<std::string>& files,
  554. const std::string& baseDir)
  555. {
  556. Json::Value result = Json::objectValue;
  557. if (!data.Language.empty()) {
  558. result[kLANGUAGE_KEY] = data.Language;
  559. if (!data.Flags.empty()) {
  560. result[kCOMPILE_FLAGS_KEY] = data.Flags;
  561. }
  562. if (!data.IncludePathList.empty()) {
  563. Json::Value includes = Json::arrayValue;
  564. for (const auto& i : data.IncludePathList) {
  565. Json::Value tmp = Json::objectValue;
  566. tmp[kPATH_KEY] = i.first;
  567. if (i.second) {
  568. tmp[kIS_SYSTEM_KEY] = i.second;
  569. }
  570. includes.append(tmp);
  571. }
  572. result[kINCLUDE_PATH_KEY] = includes;
  573. }
  574. if (!data.Defines.empty()) {
  575. result[kDEFINES_KEY] = fromStringList(data.Defines);
  576. }
  577. }
  578. result[kIS_GENERATED_KEY] = data.IsGenerated;
  579. Json::Value sourcesValue = Json::arrayValue;
  580. for (const auto& i : files) {
  581. const std::string relPath =
  582. cmSystemTools::RelativePath(baseDir.c_str(), i.c_str());
  583. sourcesValue.append(relPath.size() < i.size() ? relPath : i);
  584. }
  585. result[kSOURCES_KEY] = sourcesValue;
  586. return result;
  587. }
  588. static Json::Value DumpSourceFilesList(
  589. cmGeneratorTarget* target, const std::string& config,
  590. const std::map<std::string, LanguageData>& languageDataMap)
  591. {
  592. // Collect sourcefile groups:
  593. std::vector<cmSourceFile*> files;
  594. target->GetSourceFiles(files, config);
  595. std::unordered_map<LanguageData, std::vector<std::string> > fileGroups;
  596. for (cmSourceFile* file : files) {
  597. LanguageData fileData;
  598. fileData.Language = file->GetLanguage();
  599. if (!fileData.Language.empty()) {
  600. const LanguageData& ld = languageDataMap.at(fileData.Language);
  601. cmLocalGenerator* lg = target->GetLocalGenerator();
  602. std::string compileFlags = ld.Flags;
  603. if (const char* cflags = file->GetProperty("COMPILE_FLAGS")) {
  604. cmGeneratorExpression ge;
  605. auto cge = ge.Parse(cflags);
  606. const char* processed =
  607. cge->Evaluate(target->GetLocalGenerator(), config);
  608. lg->AppendFlags(compileFlags, processed);
  609. }
  610. fileData.Flags = compileFlags;
  611. fileData.IncludePathList = ld.IncludePathList;
  612. std::set<std::string> defines;
  613. lg->AppendDefines(defines, file->GetProperty("COMPILE_DEFINITIONS"));
  614. const std::string defPropName =
  615. "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config);
  616. lg->AppendDefines(defines, file->GetProperty(defPropName));
  617. defines.insert(ld.Defines.begin(), ld.Defines.end());
  618. fileData.SetDefines(defines);
  619. }
  620. fileData.IsGenerated = file->GetPropertyAsBool("GENERATED");
  621. std::vector<std::string>& groupFileList = fileGroups[fileData];
  622. groupFileList.push_back(file->GetFullPath());
  623. }
  624. const std::string baseDir = target->Makefile->GetCurrentSourceDirectory();
  625. Json::Value result = Json::arrayValue;
  626. for (auto it = fileGroups.begin(); it != fileGroups.end(); ++it) {
  627. Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir);
  628. if (!group.isNull()) {
  629. result.append(group);
  630. }
  631. }
  632. return result;
  633. }
  634. static Json::Value DumpTarget(cmGeneratorTarget* target,
  635. const std::string& config)
  636. {
  637. cmLocalGenerator* lg = target->GetLocalGenerator();
  638. const cmState* state = lg->GetState();
  639. const cmStateEnums::TargetType type = target->GetType();
  640. const std::string typeName = state->GetTargetTypeName(type);
  641. Json::Value ttl = Json::arrayValue;
  642. ttl.append("EXECUTABLE");
  643. ttl.append("STATIC_LIBRARY");
  644. ttl.append("SHARED_LIBRARY");
  645. ttl.append("MODULE_LIBRARY");
  646. ttl.append("OBJECT_LIBRARY");
  647. ttl.append("UTILITY");
  648. ttl.append("INTERFACE_LIBRARY");
  649. if (!hasString(ttl, typeName) || target->IsImported()) {
  650. return Json::Value();
  651. }
  652. Json::Value result = Json::objectValue;
  653. result[kNAME_KEY] = target->GetName();
  654. result[kTYPE_KEY] = typeName;
  655. result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory();
  656. result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory();
  657. if (type == cmStateEnums::INTERFACE_LIBRARY) {
  658. return result;
  659. }
  660. result[kFULL_NAME_KEY] = target->GetFullName(config);
  661. if (target->HaveWellDefinedOutputFiles()) {
  662. Json::Value artifacts = Json::arrayValue;
  663. artifacts.append(
  664. target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact));
  665. if (target->IsDLLPlatform()) {
  666. artifacts.append(
  667. target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
  668. const cmGeneratorTarget::OutputInfo* output =
  669. target->GetOutputInfo(config);
  670. if (output && !output->PdbDir.empty()) {
  671. artifacts.append(output->PdbDir + '/' + target->GetPDBName(config));
  672. }
  673. }
  674. result[kARTIFACTS_KEY] = artifacts;
  675. result[kLINKER_LANGUAGE_KEY] = target->GetLinkerLanguage(config);
  676. std::string linkLibs;
  677. std::string linkFlags;
  678. std::string linkLanguageFlags;
  679. std::string frameworkPath;
  680. std::string linkPath;
  681. cmLinkLineComputer linkLineComputer(lg,
  682. lg->GetStateSnapshot().GetDirectory());
  683. lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags,
  684. linkFlags, frameworkPath, linkPath, target);
  685. linkLibs = cmSystemTools::TrimWhitespace(linkLibs);
  686. linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
  687. linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags);
  688. frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath);
  689. linkPath = cmSystemTools::TrimWhitespace(linkPath);
  690. if (!cmSystemTools::TrimWhitespace(linkLibs).empty()) {
  691. result[kLINK_LIBRARIES_KEY] = linkLibs;
  692. }
  693. if (!cmSystemTools::TrimWhitespace(linkFlags).empty()) {
  694. result[kLINK_FLAGS_KEY] = linkFlags;
  695. }
  696. if (!cmSystemTools::TrimWhitespace(linkLanguageFlags).empty()) {
  697. result[kLINK_LANGUAGE_FLAGS_KEY] = linkLanguageFlags;
  698. }
  699. if (!frameworkPath.empty()) {
  700. result[kFRAMEWORK_PATH_KEY] = frameworkPath;
  701. }
  702. if (!linkPath.empty()) {
  703. result[kLINK_PATH_KEY] = linkPath;
  704. }
  705. const std::string sysroot =
  706. lg->GetMakefile()->GetSafeDefinition("CMAKE_SYSROOT");
  707. if (!sysroot.empty()) {
  708. result[kSYSROOT_KEY] = sysroot;
  709. }
  710. }
  711. std::set<std::string> languages;
  712. target->GetLanguages(languages, config);
  713. std::map<std::string, LanguageData> languageDataMap;
  714. for (const auto& lang : languages) {
  715. LanguageData& ld = languageDataMap[lang];
  716. ld.Language = lang;
  717. lg->GetTargetCompileFlags(target, config, lang, ld.Flags);
  718. std::set<std::string> defines;
  719. lg->GetTargetDefines(target, config, lang, defines);
  720. ld.SetDefines(defines);
  721. std::vector<std::string> includePathList;
  722. lg->GetIncludeDirectories(includePathList, target, lang, config, true);
  723. for (auto i : includePathList) {
  724. ld.IncludePathList.push_back(
  725. std::make_pair(i, target->IsSystemIncludeDirectory(i, config)));
  726. }
  727. }
  728. Json::Value sourceGroupsValue =
  729. DumpSourceFilesList(target, config, languageDataMap);
  730. if (!sourceGroupsValue.empty()) {
  731. result[kFILE_GROUPS_KEY] = sourceGroupsValue;
  732. }
  733. return result;
  734. }
  735. static Json::Value DumpTargetsList(
  736. const std::vector<cmLocalGenerator*>& generators, const std::string& config)
  737. {
  738. Json::Value result = Json::arrayValue;
  739. std::vector<cmGeneratorTarget*> targetList;
  740. for (const auto& lgIt : generators) {
  741. auto list = lgIt->GetGeneratorTargets();
  742. targetList.insert(targetList.end(), list.begin(), list.end());
  743. }
  744. std::sort(targetList.begin(), targetList.end());
  745. for (cmGeneratorTarget* target : targetList) {
  746. Json::Value tmp = DumpTarget(target, config);
  747. if (!tmp.isNull()) {
  748. result.append(tmp);
  749. }
  750. }
  751. return result;
  752. }
  753. static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
  754. {
  755. Json::Value result = Json::arrayValue;
  756. auto globalGen = cm->GetGlobalGenerator();
  757. for (const auto& projectIt : globalGen->GetProjectMap()) {
  758. Json::Value pObj = Json::objectValue;
  759. pObj[kNAME_KEY] = projectIt.first;
  760. // All Projects must have at least one local generator
  761. assert(!projectIt.second.empty());
  762. const cmLocalGenerator* lg = projectIt.second.at(0);
  763. // Project structure information:
  764. const cmMakefile* mf = lg->GetMakefile();
  765. pObj[kSOURCE_DIRECTORY_KEY] = mf->GetCurrentSourceDirectory();
  766. pObj[kBUILD_DIRECTORY_KEY] = mf->GetCurrentBinaryDirectory();
  767. pObj[kTARGETS_KEY] = DumpTargetsList(projectIt.second, config);
  768. result.append(pObj);
  769. }
  770. return result;
  771. }
  772. static Json::Value DumpConfiguration(const cmake* cm,
  773. const std::string& config)
  774. {
  775. Json::Value result = Json::objectValue;
  776. result[kNAME_KEY] = config;
  777. result[kPROJECTS_KEY] = DumpProjectList(cm, config);
  778. return result;
  779. }
  780. static Json::Value DumpConfigurationsList(const cmake* cm)
  781. {
  782. Json::Value result = Json::arrayValue;
  783. for (const std::string& c : getConfigurations(cm)) {
  784. result.append(DumpConfiguration(cm, c));
  785. }
  786. return result;
  787. }
  788. cmServerResponse cmServerProtocol1::ProcessCodeModel(
  789. const cmServerRequest& request)
  790. {
  791. if (this->m_State != STATE_COMPUTED) {
  792. return request.ReportError("No build system was generated yet.");
  793. }
  794. Json::Value result = Json::objectValue;
  795. result[kCONFIGURATIONS_KEY] = DumpConfigurationsList(this->CMakeInstance());
  796. return request.Reply(result);
  797. }
  798. cmServerResponse cmServerProtocol1::ProcessCompute(
  799. const cmServerRequest& request)
  800. {
  801. if (this->m_State > STATE_CONFIGURED) {
  802. return request.ReportError("This build system was already generated.");
  803. }
  804. if (this->m_State < STATE_CONFIGURED) {
  805. return request.ReportError("This project was not configured yet.");
  806. }
  807. cmake* cm = this->CMakeInstance();
  808. int ret = cm->Generate();
  809. if (ret < 0) {
  810. return request.ReportError("Failed to compute build system.");
  811. }
  812. m_State = STATE_COMPUTED;
  813. return request.Reply(Json::Value());
  814. }
  815. cmServerResponse cmServerProtocol1::ProcessConfigure(
  816. const cmServerRequest& request)
  817. {
  818. if (this->m_State == STATE_INACTIVE) {
  819. return request.ReportError("This instance is inactive.");
  820. }
  821. FileMonitor()->StopMonitoring();
  822. std::string errorMessage;
  823. cmake* cm = this->CMakeInstance();
  824. this->GeneratorInfo.SetupGenerator(cm, &errorMessage);
  825. if (!errorMessage.empty()) {
  826. return request.ReportError(errorMessage);
  827. }
  828. // Make sure the types of cacheArguments matches (if given):
  829. std::vector<std::string> cacheArgs = { "unused" };
  830. bool cacheArgumentsError = false;
  831. const Json::Value passedArgs = request.Data[kCACHE_ARGUMENTS_KEY];
  832. if (!passedArgs.isNull()) {
  833. if (passedArgs.isString()) {
  834. cacheArgs.push_back(passedArgs.asString());
  835. } else if (passedArgs.isArray()) {
  836. for (auto i = passedArgs.begin(); i != passedArgs.end(); ++i) {
  837. if (!i->isString()) {
  838. cacheArgumentsError = true;
  839. break;
  840. }
  841. cacheArgs.push_back(i->asString());
  842. }
  843. } else {
  844. cacheArgumentsError = true;
  845. }
  846. }
  847. if (cacheArgumentsError) {
  848. request.ReportError(
  849. "cacheArguments must be unset, a string or an array of strings.");
  850. }
  851. std::string sourceDir = cm->GetHomeDirectory();
  852. const std::string buildDir = cm->GetHomeOutputDirectory();
  853. cmGlobalGenerator* gg = cm->GetGlobalGenerator();
  854. if (buildDir.empty()) {
  855. return request.ReportError("No build directory set via Handshake.");
  856. }
  857. if (cm->LoadCache(buildDir)) {
  858. // build directory has been set up before
  859. const char* cachedSourceDir =
  860. cm->GetState()->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  861. if (!cachedSourceDir) {
  862. return request.ReportError("No CMAKE_HOME_DIRECTORY found in cache.");
  863. }
  864. if (sourceDir.empty()) {
  865. sourceDir = std::string(cachedSourceDir);
  866. cm->SetHomeDirectory(sourceDir);
  867. }
  868. const char* cachedGenerator =
  869. cm->GetState()->GetInitializedCacheValue("CMAKE_GENERATOR");
  870. if (cachedGenerator) {
  871. if (gg && gg->GetName() != cachedGenerator) {
  872. return request.ReportError("Configured generator does not match with "
  873. "CMAKE_GENERATOR found in cache.");
  874. }
  875. }
  876. } else {
  877. // build directory has not been set up before
  878. if (sourceDir.empty()) {
  879. return request.ReportError("No sourceDirectory set via "
  880. "setGlobalSettings and no cache found in "
  881. "buildDirectory.");
  882. }
  883. }
  884. cmSystemTools::ResetErrorOccuredFlag(); // Reset error state
  885. if (cm->AddCMakePaths() != 1) {
  886. return request.ReportError("Failed to set CMake paths.");
  887. }
  888. if (!cm->SetCacheArgs(cacheArgs)) {
  889. return request.ReportError("cacheArguments could not be set.");
  890. }
  891. int ret = cm->Configure();
  892. if (ret < 0) {
  893. return request.ReportError("Configuration failed.");
  894. }
  895. std::vector<std::string> toWatchList;
  896. getCMakeInputs(gg, std::string(), buildDir, nullptr, &toWatchList, nullptr);
  897. FileMonitor()->MonitorPaths(toWatchList,
  898. [this](const std::string& p, int e, int s) {
  899. this->HandleCMakeFileChanges(p, e, s);
  900. });
  901. m_State = STATE_CONFIGURED;
  902. m_isDirty = false;
  903. return request.Reply(Json::Value());
  904. }
  905. cmServerResponse cmServerProtocol1::ProcessGlobalSettings(
  906. const cmServerRequest& request)
  907. {
  908. cmake* cm = this->CMakeInstance();
  909. Json::Value obj = Json::objectValue;
  910. // Capabilities information:
  911. obj[kCAPABILITIES_KEY] = cm->ReportCapabilitiesJson(true);
  912. obj[kDEBUG_OUTPUT_KEY] = cm->GetDebugOutput();
  913. obj[kTRACE_KEY] = cm->GetTrace();
  914. obj[kTRACE_EXPAND_KEY] = cm->GetTraceExpand();
  915. obj[kWARN_UNINITIALIZED_KEY] = cm->GetWarnUninitialized();
  916. obj[kWARN_UNUSED_KEY] = cm->GetWarnUnused();
  917. obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli();
  918. obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars();
  919. obj[kSOURCE_DIRECTORY_KEY] = this->GeneratorInfo.SourceDirectory;
  920. obj[kBUILD_DIRECTORY_KEY] = this->GeneratorInfo.BuildDirectory;
  921. // Currently used generator:
  922. obj[kGENERATOR_KEY] = this->GeneratorInfo.GeneratorName;
  923. obj[kEXTRA_GENERATOR_KEY] = this->GeneratorInfo.ExtraGeneratorName;
  924. return request.Reply(obj);
  925. }
  926. static void setBool(const cmServerRequest& request, const std::string& key,
  927. std::function<void(bool)> const& setter)
  928. {
  929. if (request.Data[key].isNull()) {
  930. return;
  931. }
  932. setter(request.Data[key].asBool());
  933. }
  934. cmServerResponse cmServerProtocol1::ProcessSetGlobalSettings(
  935. const cmServerRequest& request)
  936. {
  937. const std::vector<std::string> boolValues = {
  938. kDEBUG_OUTPUT_KEY, kTRACE_KEY, kTRACE_EXPAND_KEY,
  939. kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY,
  940. kCHECK_SYSTEM_VARS_KEY
  941. };
  942. for (const auto& i : boolValues) {
  943. if (!request.Data[i].isNull() && !request.Data[i].isBool()) {
  944. return request.ReportError("\"" + i +
  945. "\" must be unset or a bool value.");
  946. }
  947. }
  948. cmake* cm = this->CMakeInstance();
  949. setBool(request, kDEBUG_OUTPUT_KEY,
  950. [cm](bool e) { cm->SetDebugOutputOn(e); });
  951. setBool(request, kTRACE_KEY, [cm](bool e) { cm->SetTrace(e); });
  952. setBool(request, kTRACE_EXPAND_KEY, [cm](bool e) { cm->SetTraceExpand(e); });
  953. setBool(request, kWARN_UNINITIALIZED_KEY,
  954. [cm](bool e) { cm->SetWarnUninitialized(e); });
  955. setBool(request, kWARN_UNUSED_KEY, [cm](bool e) { cm->SetWarnUnused(e); });
  956. setBool(request, kWARN_UNUSED_CLI_KEY,
  957. [cm](bool e) { cm->SetWarnUnusedCli(e); });
  958. setBool(request, kCHECK_SYSTEM_VARS_KEY,
  959. [cm](bool e) { cm->SetCheckSystemVars(e); });
  960. return request.Reply(Json::Value());
  961. }
  962. cmServerResponse cmServerProtocol1::ProcessFileSystemWatchers(
  963. const cmServerRequest& request)
  964. {
  965. const cmFileMonitor* const fm = FileMonitor();
  966. Json::Value result = Json::objectValue;
  967. Json::Value files = Json::arrayValue;
  968. for (const auto& f : fm->WatchedFiles()) {
  969. files.append(f);
  970. }
  971. Json::Value directories = Json::arrayValue;
  972. for (const auto& d : fm->WatchedDirectories()) {
  973. directories.append(d);
  974. }
  975. result[kWATCHED_FILES_KEY] = files;
  976. result[kWATCHED_DIRECTORIES_KEY] = directories;
  977. return request.Reply(result);
  978. }
  979. cmServerProtocol1::GeneratorInformation::GeneratorInformation(
  980. const std::string& generatorName, const std::string& extraGeneratorName,
  981. const std::string& toolset, const std::string& platform,
  982. const std::string& sourceDirectory, const std::string& buildDirectory)
  983. : GeneratorName(generatorName)
  984. , ExtraGeneratorName(extraGeneratorName)
  985. , Toolset(toolset)
  986. , Platform(platform)
  987. , SourceDirectory(sourceDirectory)
  988. , BuildDirectory(buildDirectory)
  989. {
  990. }
  991. void cmServerProtocol1::GeneratorInformation::SetupGenerator(
  992. cmake* cm, std::string* errorMessage)
  993. {
  994. const std::string fullGeneratorName =
  995. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  996. GeneratorName, ExtraGeneratorName);
  997. cm->SetHomeDirectory(SourceDirectory);
  998. cm->SetHomeOutputDirectory(BuildDirectory);
  999. cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
  1000. if (!gg) {
  1001. setErrorMessage(
  1002. errorMessage,
  1003. std::string("Could not set up the requested combination of \"") +
  1004. kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"");
  1005. return;
  1006. }
  1007. cm->SetGlobalGenerator(gg);
  1008. cm->SetGeneratorToolset(Toolset);
  1009. cm->SetGeneratorPlatform(Platform);
  1010. }