cmServerProtocol.cxx 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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. cmSystemTools::ResetErrorOccuredFlag(); // Reset error state
  844. if (cm->AddCMakePaths() != 1) {
  845. return request.ReportError("Failed to set CMake paths.");
  846. }
  847. if (!cm->SetCacheArgs(cacheArgs)) {
  848. return request.ReportError("cacheArguments could not be set.");
  849. }
  850. int ret = cm->Configure();
  851. if (ret < 0) {
  852. return request.ReportError("Configuration failed.");
  853. }
  854. std::vector<std::string> toWatchList;
  855. getCMakeInputs(gg, std::string(), buildDir, nullptr, &toWatchList, nullptr);
  856. FileMonitor()->MonitorPaths(toWatchList,
  857. [this](const std::string& p, int e, int s) {
  858. this->HandleCMakeFileChanges(p, e, s);
  859. });
  860. m_State = STATE_CONFIGURED;
  861. m_isDirty = false;
  862. return request.Reply(Json::Value());
  863. }
  864. cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
  865. const cmServerRequest& request)
  866. {
  867. cmake* cm = this->CMakeInstance();
  868. Json::Value obj = Json::objectValue;
  869. // Capabilities information:
  870. obj[kCAPABILITIES_KEY] = cm->ReportCapabilitiesJson(true);
  871. obj[kDEBUG_OUTPUT_KEY] = cm->GetDebugOutput();
  872. obj[kTRACE_KEY] = cm->GetTrace();
  873. obj[kTRACE_EXPAND_KEY] = cm->GetTraceExpand();
  874. obj[kWARN_UNINITIALIZED_KEY] = cm->GetWarnUninitialized();
  875. obj[kWARN_UNUSED_KEY] = cm->GetWarnUnused();
  876. obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli();
  877. obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars();
  878. obj[kSOURCE_DIRECTORY_KEY] = this->GeneratorInfo.SourceDirectory;
  879. obj[kBUILD_DIRECTORY_KEY] = this->GeneratorInfo.BuildDirectory;
  880. // Currently used generator:
  881. obj[kGENERATOR_KEY] = this->GeneratorInfo.GeneratorName;
  882. obj[kEXTRA_GENERATOR_KEY] = this->GeneratorInfo.ExtraGeneratorName;
  883. return request.Reply(obj);
  884. }
  885. static void setBool(const cmServerRequest& request, const std::string& key,
  886. std::function<void(bool)> setter)
  887. {
  888. if (request.Data[key].isNull()) {
  889. return;
  890. }
  891. setter(request.Data[key].asBool());
  892. }
  893. cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
  894. const cmServerRequest& request)
  895. {
  896. const std::vector<std::string> boolValues = {
  897. kDEBUG_OUTPUT_KEY, kTRACE_KEY, kTRACE_EXPAND_KEY,
  898. kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY,
  899. kCHECK_SYSTEM_VARS_KEY
  900. };
  901. for (auto i : boolValues) {
  902. if (!request.Data[i].isNull() && !request.Data[i].isBool()) {
  903. return request.ReportError("\"" + i +
  904. "\" must be unset or a bool value.");
  905. }
  906. }
  907. cmake* cm = this->CMakeInstance();
  908. setBool(request, kDEBUG_OUTPUT_KEY,
  909. [cm](bool e) { cm->SetDebugOutputOn(e); });
  910. setBool(request, kTRACE_KEY, [cm](bool e) { cm->SetTrace(e); });
  911. setBool(request, kTRACE_EXPAND_KEY, [cm](bool e) { cm->SetTraceExpand(e); });
  912. setBool(request, kWARN_UNINITIALIZED_KEY,
  913. [cm](bool e) { cm->SetWarnUninitialized(e); });
  914. setBool(request, kWARN_UNUSED_KEY, [cm](bool e) { cm->SetWarnUnused(e); });
  915. setBool(request, kWARN_UNUSED_CLI_KEY,
  916. [cm](bool e) { cm->SetWarnUnusedCli(e); });
  917. setBool(request, kCHECK_SYSTEM_VARS_KEY,
  918. [cm](bool e) { cm->SetCheckSystemVars(e); });
  919. return request.Reply(Json::Value());
  920. }
  921. cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
  922. const cmServerRequest& request)
  923. {
  924. const cmFileMonitor* const fm = FileMonitor();
  925. Json::Value result = Json::objectValue;
  926. Json::Value files = Json::arrayValue;
  927. for (const auto& f : fm->WatchedFiles()) {
  928. files.append(f);
  929. }
  930. Json::Value directories = Json::arrayValue;
  931. for (const auto& d : fm->WatchedDirectories()) {
  932. directories.append(d);
  933. }
  934. result[kWATCHED_FILES_KEY] = files;
  935. result[kWATCHED_DIRECTORIES_KEY] = directories;
  936. return request.Reply(result);
  937. }
  938. cmServerProtocol1_0::GeneratorInformation::GeneratorInformation(
  939. const std::string& generatorName, const std::string& extraGeneratorName,
  940. const std::string& toolset, const std::string& platform,
  941. const std::string& sourceDirectory, const std::string& buildDirectory)
  942. : GeneratorName(generatorName)
  943. , ExtraGeneratorName(extraGeneratorName)
  944. , Toolset(toolset)
  945. , Platform(platform)
  946. , SourceDirectory(sourceDirectory)
  947. , BuildDirectory(buildDirectory)
  948. {
  949. }
  950. void cmServerProtocol1_0::GeneratorInformation::SetupGenerator(
  951. cmake* cm, std::string* errorMessage)
  952. {
  953. const std::string fullGeneratorName =
  954. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  955. GeneratorName, ExtraGeneratorName);
  956. cm->SetHomeDirectory(SourceDirectory);
  957. cm->SetHomeOutputDirectory(BuildDirectory);
  958. cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
  959. if (!gg) {
  960. setErrorMessage(
  961. errorMessage,
  962. std::string("Could not set up the requested combination of \"") +
  963. kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"");
  964. return;
  965. }
  966. cm->SetGlobalGenerator(gg);
  967. cm->SetGeneratorToolset(Toolset);
  968. cm->SetGeneratorPlatform(Platform);
  969. }