cmServerProtocol.cxx 33 KB

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