cmServerProtocol.cxx 34 KB

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