cmServerProtocol.cxx 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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, 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 = std::make_unique<cmake>(cmake::RoleProject);
  193. const bool result = this->DoActivate(request, errorMessage);
  194. if (!result) {
  195. this->m_CMakeInstance = CM_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_0::ProtocolVersion() const
  220. {
  221. return std::make_pair(1, 0);
  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. const std::string suffix = "/CMakeLists.txt";
  235. const std::string cachedValueCML = cachedValue + suffix;
  236. const std::string valueCML = value + suffix;
  237. if (!cmSystemTools::SameFile(valueCML, cachedValueCML)) {
  238. setErrorMessage(errorMessage,
  239. std::string("\"CMAKE_HOME_DIRECTORY\" is set but "
  240. "incompatible with configured "
  241. "source directory value."));
  242. return false;
  243. }
  244. if (value.empty()) {
  245. value = cachedValue;
  246. }
  247. return true;
  248. }
  249. static bool testValue(cmState* state, const std::string& key,
  250. std::string& value, const std::string& keyDescription,
  251. std::string* errorMessage)
  252. {
  253. const std::string cachedValue = std::string(state->GetCacheEntryValue(key));
  254. if (!cachedValue.empty() && !value.empty() && cachedValue != value) {
  255. setErrorMessage(errorMessage, std::string("\"") + key +
  256. "\" is set but incompatible with configured " +
  257. keyDescription + " value.");
  258. return false;
  259. }
  260. if (value.empty()) {
  261. value = cachedValue;
  262. }
  263. return true;
  264. }
  265. bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
  266. std::string* errorMessage)
  267. {
  268. std::string sourceDirectory = request.Data[kSOURCE_DIRECTORY_KEY].asString();
  269. const std::string buildDirectory =
  270. request.Data[kBUILD_DIRECTORY_KEY].asString();
  271. std::string generator = request.Data[kGENERATOR_KEY].asString();
  272. std::string extraGenerator = request.Data[kEXTRA_GENERATOR_KEY].asString();
  273. std::string toolset = request.Data[kTOOLSET_KEY].asString();
  274. std::string platform = request.Data[kPLATFORM_KEY].asString();
  275. if (buildDirectory.empty()) {
  276. setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY +
  277. "\" is missing.");
  278. return false;
  279. }
  280. cmake* cm = CMakeInstance();
  281. if (cmSystemTools::PathExists(buildDirectory)) {
  282. if (!cmSystemTools::FileIsDirectory(buildDirectory)) {
  283. setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY +
  284. "\" exists but is not a directory.");
  285. return false;
  286. }
  287. const std::string cachePath = cm->FindCacheFile(buildDirectory);
  288. if (cm->LoadCache(cachePath)) {
  289. cmState* state = cm->GetState();
  290. // Check generator:
  291. if (!testValue(state, "CMAKE_GENERATOR", generator, "generator",
  292. errorMessage)) {
  293. return false;
  294. }
  295. // check extra generator:
  296. if (!testValue(state, "CMAKE_EXTRA_GENERATOR", extraGenerator,
  297. "extra generator", errorMessage)) {
  298. return false;
  299. }
  300. // check sourcedir:
  301. if (!testHomeDirectory(state, sourceDirectory, errorMessage)) {
  302. return false;
  303. }
  304. // check toolset:
  305. if (!testValue(state, "CMAKE_GENERATOR_TOOLSET", toolset, "toolset",
  306. errorMessage)) {
  307. return false;
  308. }
  309. // check platform:
  310. if (!testValue(state, "CMAKE_GENERATOR_PLATFORM", platform, "platform",
  311. errorMessage)) {
  312. return false;
  313. }
  314. }
  315. }
  316. if (sourceDirectory.empty()) {
  317. setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY +
  318. "\" is unset but required.");
  319. return false;
  320. }
  321. if (!cmSystemTools::FileIsDirectory(sourceDirectory)) {
  322. setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY +
  323. "\" is not a directory.");
  324. return false;
  325. }
  326. if (generator.empty()) {
  327. setErrorMessage(errorMessage, std::string("\"") + kGENERATOR_KEY +
  328. "\" is unset but required.");
  329. return false;
  330. }
  331. std::vector<cmake::GeneratorInfo> generators;
  332. cm->GetRegisteredGenerators(generators);
  333. auto baseIt = std::find_if(generators.begin(), generators.end(),
  334. [&generator](const cmake::GeneratorInfo& info) {
  335. return info.name == generator;
  336. });
  337. if (baseIt == generators.end()) {
  338. setErrorMessage(errorMessage, std::string("Generator \"") + generator +
  339. "\" not supported.");
  340. return false;
  341. }
  342. auto extraIt = std::find_if(
  343. generators.begin(), generators.end(),
  344. [&generator, &extraGenerator](const cmake::GeneratorInfo& info) {
  345. return info.baseName == generator && info.extraName == extraGenerator;
  346. });
  347. if (extraIt == generators.end()) {
  348. setErrorMessage(errorMessage,
  349. std::string("The combination of generator \"" + generator +
  350. "\" and extra generator \"" + extraGenerator +
  351. "\" is not supported."));
  352. return false;
  353. }
  354. if (!extraIt->supportsToolset && !toolset.empty()) {
  355. setErrorMessage(errorMessage,
  356. std::string("Toolset was provided but is not supported by "
  357. "the requested generator."));
  358. return false;
  359. }
  360. if (!extraIt->supportsPlatform && !platform.empty()) {
  361. setErrorMessage(errorMessage,
  362. std::string("Platform was provided but is not supported "
  363. "by the requested generator."));
  364. return false;
  365. }
  366. this->GeneratorInfo =
  367. GeneratorInformation(generator, extraGenerator, toolset, platform,
  368. sourceDirectory, buildDirectory);
  369. this->m_State = STATE_ACTIVE;
  370. return true;
  371. }
  372. void cmServerProtocol1_0::HandleCMakeFileChanges(const std::string& path,
  373. int event, int status)
  374. {
  375. assert(status == 0);
  376. static_cast<void>(status);
  377. if (!m_isDirty) {
  378. m_isDirty = true;
  379. SendSignal(kDIRTY_SIGNAL, Json::objectValue);
  380. }
  381. Json::Value obj = Json::objectValue;
  382. obj[kPATH_KEY] = path;
  383. Json::Value properties = Json::arrayValue;
  384. if (event & UV_RENAME) {
  385. properties.append(kRENAME_PROPERTY_VALUE);
  386. }
  387. if (event & UV_CHANGE) {
  388. properties.append(kCHANGE_PROPERTY_VALUE);
  389. }
  390. obj[kPROPERTIES_KEY] = properties;
  391. SendSignal(kFILE_CHANGE_SIGNAL, obj);
  392. }
  393. const cmServerResponse cmServerProtocol1_0::Process(
  394. const cmServerRequest& request)
  395. {
  396. assert(this->m_State >= STATE_ACTIVE);
  397. if (request.Type == kCACHE_TYPE) {
  398. return this->ProcessCache(request);
  399. }
  400. if (request.Type == kCMAKE_INPUTS_TYPE) {
  401. return this->ProcessCMakeInputs(request);
  402. }
  403. if (request.Type == kCODE_MODEL_TYPE) {
  404. return this->ProcessCodeModel(request);
  405. }
  406. if (request.Type == kCOMPUTE_TYPE) {
  407. return this->ProcessCompute(request);
  408. }
  409. if (request.Type == kCONFIGURE_TYPE) {
  410. return this->ProcessConfigure(request);
  411. }
  412. if (request.Type == kFILESYSTEM_WATCHERS_TYPE) {
  413. return this->ProcessFileSystemWatchers(request);
  414. }
  415. if (request.Type == kGLOBAL_SETTINGS_TYPE) {
  416. return this->ProcessGlobalSettings(request);
  417. }
  418. if (request.Type == kSET_GLOBAL_SETTINGS_TYPE) {
  419. return this->ProcessSetGlobalSettings(request);
  420. }
  421. return request.ReportError("Unknown command!");
  422. }
  423. bool cmServerProtocol1_0::IsExperimental() const
  424. {
  425. return true;
  426. }
  427. cmServerResponse cmServerProtocol1_0::ProcessCache(
  428. const cmServerRequest& request)
  429. {
  430. if (this->m_State < STATE_CONFIGURED) {
  431. return request.ReportError("This project was not configured yet.");
  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 (const auto& 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 (const auto& 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 (const auto& 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_0::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. for (const auto& i : defines) {
  527. result.push_back(i);
  528. }
  529. std::sort(result.begin(), result.end());
  530. Defines = result;
  531. }
  532. namespace std {
  533. template <>
  534. struct hash<LanguageData>
  535. {
  536. std::size_t operator()(const LanguageData& in) const
  537. {
  538. using std::hash;
  539. size_t result =
  540. hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags);
  541. for (const auto& i : in.IncludePathList) {
  542. result = result ^ (hash<std::string>()(i.first) ^
  543. (i.second ? std::numeric_limits<size_t>::max() : 0));
  544. }
  545. for (const auto& i : in.Defines) {
  546. result = result ^ hash<std::string>()(i);
  547. }
  548. result =
  549. result ^ (in.IsGenerated ? std::numeric_limits<size_t>::max() : 0);
  550. return result;
  551. }
  552. };
  553. } // namespace std
  554. static Json::Value DumpSourceFileGroup(const LanguageData& data,
  555. const std::vector<std::string>& files,
  556. const std::string& baseDir)
  557. {
  558. Json::Value result = Json::objectValue;
  559. if (!data.Language.empty()) {
  560. result[kLANGUAGE_KEY] = data.Language;
  561. if (!data.Flags.empty()) {
  562. result[kCOMPILE_FLAGS_KEY] = data.Flags;
  563. }
  564. if (!data.IncludePathList.empty()) {
  565. Json::Value includes = Json::arrayValue;
  566. for (const auto& i : data.IncludePathList) {
  567. Json::Value tmp = Json::objectValue;
  568. tmp[kPATH_KEY] = i.first;
  569. if (i.second) {
  570. tmp[kIS_SYSTEM_KEY] = i.second;
  571. }
  572. includes.append(tmp);
  573. }
  574. result[kINCLUDE_PATH_KEY] = includes;
  575. }
  576. if (!data.Defines.empty()) {
  577. result[kDEFINES_KEY] = fromStringList(data.Defines);
  578. }
  579. }
  580. result[kIS_GENERATED_KEY] = data.IsGenerated;
  581. Json::Value sourcesValue = Json::arrayValue;
  582. for (const auto& i : files) {
  583. const std::string relPath =
  584. cmSystemTools::RelativePath(baseDir.c_str(), i.c_str());
  585. sourcesValue.append(relPath.size() < i.size() ? relPath : i);
  586. }
  587. result[kSOURCES_KEY] = sourcesValue;
  588. return result;
  589. }
  590. static Json::Value DumpSourceFilesList(
  591. cmGeneratorTarget* target, const std::string& config,
  592. const std::map<std::string, LanguageData>& languageDataMap)
  593. {
  594. // Collect sourcefile groups:
  595. std::vector<cmSourceFile*> files;
  596. target->GetSourceFiles(files, config);
  597. std::unordered_map<LanguageData, std::vector<std::string> > fileGroups;
  598. for (cmSourceFile* file : files) {
  599. LanguageData fileData;
  600. fileData.Language = file->GetLanguage();
  601. if (!fileData.Language.empty()) {
  602. const LanguageData& ld = languageDataMap.at(fileData.Language);
  603. cmLocalGenerator* lg = target->GetLocalGenerator();
  604. std::string compileFlags = ld.Flags;
  605. if (const char* cflags = file->GetProperty("COMPILE_FLAGS")) {
  606. cmGeneratorExpression ge;
  607. auto cge = ge.Parse(cflags);
  608. const char* processed =
  609. cge->Evaluate(target->GetLocalGenerator(), config);
  610. lg->AppendFlags(compileFlags, processed);
  611. }
  612. fileData.Flags = compileFlags;
  613. fileData.IncludePathList = ld.IncludePathList;
  614. std::set<std::string> defines;
  615. lg->AppendDefines(defines, file->GetProperty("COMPILE_DEFINITIONS"));
  616. const std::string defPropName =
  617. "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config);
  618. lg->AppendDefines(defines, file->GetProperty(defPropName));
  619. defines.insert(ld.Defines.begin(), ld.Defines.end());
  620. fileData.SetDefines(defines);
  621. }
  622. fileData.IsGenerated = file->GetPropertyAsBool("GENERATED");
  623. std::vector<std::string>& groupFileList = fileGroups[fileData];
  624. groupFileList.push_back(file->GetFullPath());
  625. }
  626. const std::string baseDir = target->Makefile->GetCurrentSourceDirectory();
  627. Json::Value result = Json::arrayValue;
  628. for (auto it = fileGroups.begin(); it != fileGroups.end(); ++it) {
  629. Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir);
  630. if (!group.isNull()) {
  631. result.append(group);
  632. }
  633. }
  634. return result;
  635. }
  636. static Json::Value DumpTarget(cmGeneratorTarget* target,
  637. const std::string& config)
  638. {
  639. cmLocalGenerator* lg = target->GetLocalGenerator();
  640. const cmState* state = lg->GetState();
  641. const cmStateEnums::TargetType type = target->GetType();
  642. const std::string typeName = state->GetTargetTypeName(type);
  643. Json::Value ttl = Json::arrayValue;
  644. ttl.append("EXECUTABLE");
  645. ttl.append("STATIC_LIBRARY");
  646. ttl.append("SHARED_LIBRARY");
  647. ttl.append("MODULE_LIBRARY");
  648. ttl.append("OBJECT_LIBRARY");
  649. ttl.append("UTILITY");
  650. ttl.append("INTERFACE_LIBRARY");
  651. if (!hasString(ttl, typeName) || target->IsImported()) {
  652. return Json::Value();
  653. }
  654. Json::Value result = Json::objectValue;
  655. result[kNAME_KEY] = target->GetName();
  656. result[kTYPE_KEY] = typeName;
  657. result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory();
  658. result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory();
  659. if (type == cmStateEnums::INTERFACE_LIBRARY) {
  660. return result;
  661. }
  662. result[kFULL_NAME_KEY] = target->GetFullName(config);
  663. if (target->HaveWellDefinedOutputFiles()) {
  664. Json::Value artifacts = Json::arrayValue;
  665. artifacts.append(
  666. target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact));
  667. if (target->IsDLLPlatform()) {
  668. artifacts.append(
  669. target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
  670. const cmGeneratorTarget::OutputInfo* output =
  671. target->GetOutputInfo(config);
  672. if (output && !output->PdbDir.empty()) {
  673. artifacts.append(output->PdbDir + '/' + target->GetPDBName(config));
  674. }
  675. }
  676. result[kARTIFACTS_KEY] = artifacts;
  677. result[kLINKER_LANGUAGE_KEY] = target->GetLinkerLanguage(config);
  678. std::string linkLibs;
  679. std::string linkFlags;
  680. std::string linkLanguageFlags;
  681. std::string frameworkPath;
  682. std::string linkPath;
  683. cmLinkLineComputer linkLineComputer(lg,
  684. lg->GetStateSnapshot().GetDirectory());
  685. lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags,
  686. linkFlags, frameworkPath, linkPath, target);
  687. linkLibs = cmSystemTools::TrimWhitespace(linkLibs);
  688. linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
  689. linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags);
  690. frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath);
  691. linkPath = cmSystemTools::TrimWhitespace(linkPath);
  692. if (!cmSystemTools::TrimWhitespace(linkLibs).empty()) {
  693. result[kLINK_LIBRARIES_KEY] = linkLibs;
  694. }
  695. if (!cmSystemTools::TrimWhitespace(linkFlags).empty()) {
  696. result[kLINK_FLAGS_KEY] = linkFlags;
  697. }
  698. if (!cmSystemTools::TrimWhitespace(linkLanguageFlags).empty()) {
  699. result[kLINK_LANGUAGE_FLAGS_KEY] = linkLanguageFlags;
  700. }
  701. if (!frameworkPath.empty()) {
  702. result[kFRAMEWORK_PATH_KEY] = frameworkPath;
  703. }
  704. if (!linkPath.empty()) {
  705. result[kLINK_PATH_KEY] = linkPath;
  706. }
  707. const std::string sysroot =
  708. lg->GetMakefile()->GetSafeDefinition("CMAKE_SYSROOT");
  709. if (!sysroot.empty()) {
  710. result[kSYSROOT_KEY] = sysroot;
  711. }
  712. }
  713. std::set<std::string> languages;
  714. target->GetLanguages(languages, config);
  715. std::map<std::string, LanguageData> languageDataMap;
  716. for (const auto& lang : languages) {
  717. LanguageData& ld = languageDataMap[lang];
  718. ld.Language = lang;
  719. lg->GetTargetCompileFlags(target, config, lang, ld.Flags);
  720. std::set<std::string> defines;
  721. lg->GetTargetDefines(target, config, lang, defines);
  722. ld.SetDefines(defines);
  723. std::vector<std::string> includePathList;
  724. lg->GetIncludeDirectories(includePathList, target, lang, config, true);
  725. for (auto i : includePathList) {
  726. ld.IncludePathList.push_back(
  727. std::make_pair(i, target->IsSystemIncludeDirectory(i, config)));
  728. }
  729. }
  730. Json::Value sourceGroupsValue =
  731. DumpSourceFilesList(target, config, languageDataMap);
  732. if (!sourceGroupsValue.empty()) {
  733. result[kFILE_GROUPS_KEY] = sourceGroupsValue;
  734. }
  735. return result;
  736. }
  737. static Json::Value DumpTargetsList(
  738. const std::vector<cmLocalGenerator*>& generators, const std::string& config)
  739. {
  740. Json::Value result = Json::arrayValue;
  741. std::vector<cmGeneratorTarget*> targetList;
  742. for (const auto& lgIt : generators) {
  743. auto list = lgIt->GetGeneratorTargets();
  744. targetList.insert(targetList.end(), list.begin(), list.end());
  745. }
  746. std::sort(targetList.begin(), targetList.end());
  747. for (cmGeneratorTarget* target : targetList) {
  748. Json::Value tmp = DumpTarget(target, config);
  749. if (!tmp.isNull()) {
  750. result.append(tmp);
  751. }
  752. }
  753. return result;
  754. }
  755. static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
  756. {
  757. Json::Value result = Json::arrayValue;
  758. auto globalGen = cm->GetGlobalGenerator();
  759. for (const auto& projectIt : globalGen->GetProjectMap()) {
  760. Json::Value pObj = Json::objectValue;
  761. pObj[kNAME_KEY] = projectIt.first;
  762. // All Projects must have at least one local generator
  763. assert(!projectIt.second.empty());
  764. const cmLocalGenerator* lg = projectIt.second.at(0);
  765. // Project structure information:
  766. const cmMakefile* mf = lg->GetMakefile();
  767. pObj[kSOURCE_DIRECTORY_KEY] = mf->GetCurrentSourceDirectory();
  768. pObj[kBUILD_DIRECTORY_KEY] = mf->GetCurrentBinaryDirectory();
  769. pObj[kTARGETS_KEY] = DumpTargetsList(projectIt.second, config);
  770. result.append(pObj);
  771. }
  772. return result;
  773. }
  774. static Json::Value DumpConfiguration(const cmake* cm,
  775. const std::string& config)
  776. {
  777. Json::Value result = Json::objectValue;
  778. result[kNAME_KEY] = config;
  779. result[kPROJECTS_KEY] = DumpProjectList(cm, config);
  780. return result;
  781. }
  782. static Json::Value DumpConfigurationsList(const cmake* cm)
  783. {
  784. Json::Value result = Json::arrayValue;
  785. for (const std::string& c : getConfigurations(cm)) {
  786. result.append(DumpConfiguration(cm, c));
  787. }
  788. return result;
  789. }
  790. cmServerResponse cmServerProtocol1_0::ProcessCodeModel(
  791. const cmServerRequest& request)
  792. {
  793. if (this->m_State != STATE_COMPUTED) {
  794. return request.ReportError("No build system was generated yet.");
  795. }
  796. Json::Value result = Json::objectValue;
  797. result[kCONFIGURATIONS_KEY] = DumpConfigurationsList(this->CMakeInstance());
  798. return request.Reply(result);
  799. }
  800. cmServerResponse cmServerProtocol1_0::ProcessCompute(
  801. const cmServerRequest& request)
  802. {
  803. if (this->m_State > STATE_CONFIGURED) {
  804. return request.ReportError("This build system was already generated.");
  805. }
  806. if (this->m_State < STATE_CONFIGURED) {
  807. return request.ReportError("This project was not configured yet.");
  808. }
  809. cmake* cm = this->CMakeInstance();
  810. int ret = cm->Generate();
  811. if (ret < 0) {
  812. return request.ReportError("Failed to compute build system.");
  813. }
  814. m_State = STATE_COMPUTED;
  815. return request.Reply(Json::Value());
  816. }
  817. cmServerResponse cmServerProtocol1_0::ProcessConfigure(
  818. const cmServerRequest& request)
  819. {
  820. if (this->m_State == STATE_INACTIVE) {
  821. return request.ReportError("This instance is inactive.");
  822. }
  823. FileMonitor()->StopMonitoring();
  824. std::string errorMessage;
  825. cmake* cm = this->CMakeInstance();
  826. this->GeneratorInfo.SetupGenerator(cm, &errorMessage);
  827. if (!errorMessage.empty()) {
  828. return request.ReportError(errorMessage);
  829. }
  830. // Make sure the types of cacheArguments matches (if given):
  831. std::vector<std::string> cacheArgs = { "unused" };
  832. bool cacheArgumentsError = false;
  833. const Json::Value passedArgs = request.Data[kCACHE_ARGUMENTS_KEY];
  834. if (!passedArgs.isNull()) {
  835. if (passedArgs.isString()) {
  836. cacheArgs.push_back(passedArgs.asString());
  837. } else if (passedArgs.isArray()) {
  838. for (auto i = passedArgs.begin(); i != passedArgs.end(); ++i) {
  839. if (!i->isString()) {
  840. cacheArgumentsError = true;
  841. break;
  842. }
  843. cacheArgs.push_back(i->asString());
  844. }
  845. } else {
  846. cacheArgumentsError = true;
  847. }
  848. }
  849. if (cacheArgumentsError) {
  850. request.ReportError(
  851. "cacheArguments must be unset, a string or an array of strings.");
  852. }
  853. std::string sourceDir = cm->GetHomeDirectory();
  854. const std::string buildDir = cm->GetHomeOutputDirectory();
  855. cmGlobalGenerator* gg = cm->GetGlobalGenerator();
  856. if (buildDir.empty()) {
  857. return request.ReportError("No build directory set via Handshake.");
  858. }
  859. if (cm->LoadCache(buildDir)) {
  860. // build directory has been set up before
  861. const char* cachedSourceDir =
  862. cm->GetState()->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  863. if (!cachedSourceDir) {
  864. return request.ReportError("No CMAKE_HOME_DIRECTORY found in cache.");
  865. }
  866. if (sourceDir.empty()) {
  867. sourceDir = std::string(cachedSourceDir);
  868. cm->SetHomeDirectory(sourceDir);
  869. }
  870. const char* cachedGenerator =
  871. cm->GetState()->GetInitializedCacheValue("CMAKE_GENERATOR");
  872. if (cachedGenerator) {
  873. if (gg && gg->GetName() != cachedGenerator) {
  874. return request.ReportError("Configured generator does not match with "
  875. "CMAKE_GENERATOR found in cache.");
  876. }
  877. }
  878. } else {
  879. // build directory has not been set up before
  880. if (sourceDir.empty()) {
  881. return request.ReportError("No sourceDirectory set via "
  882. "setGlobalSettings and no cache found in "
  883. "buildDirectory.");
  884. }
  885. }
  886. cmSystemTools::ResetErrorOccuredFlag(); // Reset error state
  887. if (cm->AddCMakePaths() != 1) {
  888. return request.ReportError("Failed to set CMake paths.");
  889. }
  890. if (!cm->SetCacheArgs(cacheArgs)) {
  891. return request.ReportError("cacheArguments could not be set.");
  892. }
  893. int ret = cm->Configure();
  894. if (ret < 0) {
  895. return request.ReportError("Configuration failed.");
  896. }
  897. std::vector<std::string> toWatchList;
  898. getCMakeInputs(gg, std::string(), buildDir, nullptr, &toWatchList, nullptr);
  899. FileMonitor()->MonitorPaths(toWatchList,
  900. [this](const std::string& p, int e, int s) {
  901. this->HandleCMakeFileChanges(p, e, s);
  902. });
  903. m_State = STATE_CONFIGURED;
  904. m_isDirty = false;
  905. return request.Reply(Json::Value());
  906. }
  907. cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
  908. const cmServerRequest& request)
  909. {
  910. cmake* cm = this->CMakeInstance();
  911. Json::Value obj = Json::objectValue;
  912. // Capabilities information:
  913. obj[kCAPABILITIES_KEY] = cm->ReportCapabilitiesJson(true);
  914. obj[kDEBUG_OUTPUT_KEY] = cm->GetDebugOutput();
  915. obj[kTRACE_KEY] = cm->GetTrace();
  916. obj[kTRACE_EXPAND_KEY] = cm->GetTraceExpand();
  917. obj[kWARN_UNINITIALIZED_KEY] = cm->GetWarnUninitialized();
  918. obj[kWARN_UNUSED_KEY] = cm->GetWarnUnused();
  919. obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli();
  920. obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars();
  921. obj[kSOURCE_DIRECTORY_KEY] = this->GeneratorInfo.SourceDirectory;
  922. obj[kBUILD_DIRECTORY_KEY] = this->GeneratorInfo.BuildDirectory;
  923. // Currently used generator:
  924. obj[kGENERATOR_KEY] = this->GeneratorInfo.GeneratorName;
  925. obj[kEXTRA_GENERATOR_KEY] = this->GeneratorInfo.ExtraGeneratorName;
  926. return request.Reply(obj);
  927. }
  928. static void setBool(const cmServerRequest& request, const std::string& key,
  929. std::function<void(bool)> const& setter)
  930. {
  931. if (request.Data[key].isNull()) {
  932. return;
  933. }
  934. setter(request.Data[key].asBool());
  935. }
  936. cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
  937. const cmServerRequest& request)
  938. {
  939. const std::vector<std::string> boolValues = {
  940. kDEBUG_OUTPUT_KEY, kTRACE_KEY, kTRACE_EXPAND_KEY,
  941. kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY,
  942. kCHECK_SYSTEM_VARS_KEY
  943. };
  944. for (const auto& i : boolValues) {
  945. if (!request.Data[i].isNull() && !request.Data[i].isBool()) {
  946. return request.ReportError("\"" + i +
  947. "\" must be unset or a bool value.");
  948. }
  949. }
  950. cmake* cm = this->CMakeInstance();
  951. setBool(request, kDEBUG_OUTPUT_KEY,
  952. [cm](bool e) { cm->SetDebugOutputOn(e); });
  953. setBool(request, kTRACE_KEY, [cm](bool e) { cm->SetTrace(e); });
  954. setBool(request, kTRACE_EXPAND_KEY, [cm](bool e) { cm->SetTraceExpand(e); });
  955. setBool(request, kWARN_UNINITIALIZED_KEY,
  956. [cm](bool e) { cm->SetWarnUninitialized(e); });
  957. setBool(request, kWARN_UNUSED_KEY, [cm](bool e) { cm->SetWarnUnused(e); });
  958. setBool(request, kWARN_UNUSED_CLI_KEY,
  959. [cm](bool e) { cm->SetWarnUnusedCli(e); });
  960. setBool(request, kCHECK_SYSTEM_VARS_KEY,
  961. [cm](bool e) { cm->SetCheckSystemVars(e); });
  962. return request.Reply(Json::Value());
  963. }
  964. cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
  965. const cmServerRequest& request)
  966. {
  967. const cmFileMonitor* const fm = FileMonitor();
  968. Json::Value result = Json::objectValue;
  969. Json::Value files = Json::arrayValue;
  970. for (const auto& f : fm->WatchedFiles()) {
  971. files.append(f);
  972. }
  973. Json::Value directories = Json::arrayValue;
  974. for (const auto& d : fm->WatchedDirectories()) {
  975. directories.append(d);
  976. }
  977. result[kWATCHED_FILES_KEY] = files;
  978. result[kWATCHED_DIRECTORIES_KEY] = directories;
  979. return request.Reply(result);
  980. }
  981. cmServerProtocol1_0::GeneratorInformation::GeneratorInformation(
  982. const std::string& generatorName, const std::string& extraGeneratorName,
  983. const std::string& toolset, const std::string& platform,
  984. const std::string& sourceDirectory, const std::string& buildDirectory)
  985. : GeneratorName(generatorName)
  986. , ExtraGeneratorName(extraGeneratorName)
  987. , Toolset(toolset)
  988. , Platform(platform)
  989. , SourceDirectory(sourceDirectory)
  990. , BuildDirectory(buildDirectory)
  991. {
  992. }
  993. void cmServerProtocol1_0::GeneratorInformation::SetupGenerator(
  994. cmake* cm, std::string* errorMessage)
  995. {
  996. const std::string fullGeneratorName =
  997. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  998. GeneratorName, ExtraGeneratorName);
  999. cm->SetHomeDirectory(SourceDirectory);
  1000. cm->SetHomeOutputDirectory(BuildDirectory);
  1001. cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
  1002. if (!gg) {
  1003. setErrorMessage(
  1004. errorMessage,
  1005. std::string("Could not set up the requested combination of \"") +
  1006. kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"");
  1007. return;
  1008. }
  1009. cm->SetGlobalGenerator(gg);
  1010. cm->SetGeneratorToolset(Toolset);
  1011. cm->SetGeneratorPlatform(Platform);
  1012. }