cmServerProtocol.cxx 35 KB

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