cmFindPackageCommand.cxx 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285
  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 "cmFindPackageCommand.h"
  4. #include "cmSystemTools.h"
  5. #include "cmsys/Directory.hxx"
  6. #include "cmsys/FStream.hxx"
  7. #include "cmsys/Glob.hxx"
  8. #include "cmsys/RegularExpression.hxx"
  9. #include "cmsys/String.h"
  10. #include <algorithm>
  11. #include <cassert>
  12. #include <cstdio>
  13. #include <cstring>
  14. #include <deque>
  15. #include <functional>
  16. #include <iterator>
  17. #include <sstream>
  18. #include <utility>
  19. #include "cm_memory.hxx"
  20. #include "cmAlgorithms.h"
  21. #include "cmMakefile.h"
  22. #include "cmMessageType.h"
  23. #include "cmPolicies.h"
  24. #include "cmRange.h"
  25. #include "cmSearchPath.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmVersion.h"
  30. #if defined(__HAIKU__)
  31. # include <FindDirectory.h>
  32. # include <StorageDefs.h>
  33. #endif
  34. class cmExecutionStatus;
  35. class cmFileList;
  36. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  37. "PACKAGE_REGISTRY");
  38. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  39. "BUILDS");
  40. cmFindPackageCommand::PathLabel
  41. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  42. struct StrverscmpGreater
  43. {
  44. bool operator()(const std::string& lhs, const std::string& rhs) const
  45. {
  46. return cmSystemTools::strverscmp(lhs, rhs) > 0;
  47. }
  48. };
  49. struct StrverscmpLesser
  50. {
  51. bool operator()(const std::string& lhs, const std::string& rhs) const
  52. {
  53. return cmSystemTools::strverscmp(lhs, rhs) < 0;
  54. }
  55. };
  56. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  57. std::vector<std::string>::iterator end,
  58. SortOrderType order, SortDirectionType dir)
  59. {
  60. if (order == Name_order) {
  61. if (dir == Dec) {
  62. std::sort(begin, end, std::greater<std::string>());
  63. } else {
  64. std::sort(begin, end);
  65. }
  66. } else if (order == Natural)
  67. // natural order uses letters and numbers (contiguous numbers digit are
  68. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  69. {
  70. if (dir == Dec) {
  71. std::sort(begin, end, StrverscmpGreater());
  72. } else {
  73. std::sort(begin, end, StrverscmpLesser());
  74. }
  75. }
  76. // else do not sort
  77. }
  78. cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
  79. : cmFindCommon(status)
  80. {
  81. this->CMakePathName = "PACKAGE";
  82. this->Quiet = false;
  83. this->Required = false;
  84. this->NoUserRegistry = false;
  85. this->NoSystemRegistry = false;
  86. this->UseConfigFiles = true;
  87. this->UseFindModules = true;
  88. this->DebugMode = false;
  89. this->UseLib32Paths = false;
  90. this->UseLib64Paths = false;
  91. this->UseLibx32Paths = false;
  92. this->UseRealPath = false;
  93. this->PolicyScope = true;
  94. this->VersionMajor = 0;
  95. this->VersionMinor = 0;
  96. this->VersionPatch = 0;
  97. this->VersionTweak = 0;
  98. this->VersionCount = 0;
  99. this->VersionExact = false;
  100. this->VersionFoundMajor = 0;
  101. this->VersionFoundMinor = 0;
  102. this->VersionFoundPatch = 0;
  103. this->VersionFoundTweak = 0;
  104. this->VersionFoundCount = 0;
  105. this->RequiredCMakeVersion = 0;
  106. this->SortOrder = None;
  107. this->SortDirection = Asc;
  108. this->AppendSearchPathGroups();
  109. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  110. }
  111. void cmFindPackageCommand::AppendSearchPathGroups()
  112. {
  113. std::vector<cmFindCommon::PathLabel>* labels;
  114. // Update the All group with new paths
  115. labels = &this->PathGroupLabelMap[PathGroup::All];
  116. labels->insert(
  117. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  118. PathLabel::UserRegistry);
  119. labels->insert(
  120. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  121. PathLabel::Builds);
  122. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  123. PathLabel::SystemRegistry);
  124. // Create the new path objects
  125. this->LabeledPaths.insert(
  126. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  127. this->LabeledPaths.insert(
  128. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  129. this->LabeledPaths.insert(
  130. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  131. }
  132. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
  133. {
  134. if (args.empty()) {
  135. this->SetError("called with incorrect number of arguments");
  136. return false;
  137. }
  138. // Lookup required version of CMake.
  139. if (const char* rv =
  140. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  141. unsigned int v[3] = { 0, 0, 0 };
  142. sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
  143. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  144. }
  145. // Check for debug mode.
  146. this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
  147. // Lookup target architecture, if any.
  148. if (const char* arch =
  149. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  150. this->LibraryArchitecture = arch;
  151. }
  152. // Lookup whether lib32 paths should be used.
  153. if (this->Makefile->PlatformIs32Bit() &&
  154. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  155. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  156. this->UseLib32Paths = true;
  157. }
  158. // Lookup whether lib64 paths should be used.
  159. if (this->Makefile->PlatformIs64Bit() &&
  160. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  161. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  162. this->UseLib64Paths = true;
  163. }
  164. // Lookup whether libx32 paths should be used.
  165. if (this->Makefile->PlatformIsx32() &&
  166. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  167. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  168. this->UseLibx32Paths = true;
  169. }
  170. // Check if User Package Registry should be disabled
  171. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  172. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  173. if (const char* def =
  174. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  175. this->NoUserRegistry = !cmIsOn(def);
  176. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  177. this->NoUserRegistry = true;
  178. }
  179. // Check if System Package Registry should be disabled
  180. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  181. this->NoSystemRegistry = true;
  182. }
  183. // Check whether we should resolve symlinks when finding packages
  184. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  185. this->UseRealPath = true;
  186. }
  187. // Check if Sorting should be enabled
  188. if (const char* so =
  189. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  190. if (strcmp(so, "NAME") == 0) {
  191. this->SortOrder = Name_order;
  192. } else if (strcmp(so, "NATURAL") == 0) {
  193. this->SortOrder = Natural;
  194. } else {
  195. this->SortOrder = None;
  196. }
  197. }
  198. if (const char* sd =
  199. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  200. this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec;
  201. }
  202. // Find what search path locations have been enabled/disable
  203. this->SelectDefaultSearchModes();
  204. // Find the current root path mode.
  205. this->SelectDefaultRootPathMode();
  206. // Find the current bundle/framework search policy.
  207. this->SelectDefaultMacMode();
  208. // Record options.
  209. this->Name = args[0];
  210. std::string components;
  211. const char* components_sep = "";
  212. std::set<std::string> requiredComponents;
  213. std::set<std::string> optionalComponents;
  214. // Always search directly in a generated path.
  215. this->SearchPathSuffixes.emplace_back();
  216. // Parse the arguments.
  217. enum Doing
  218. {
  219. DoingNone,
  220. DoingComponents,
  221. DoingOptionalComponents,
  222. DoingNames,
  223. DoingPaths,
  224. DoingPathSuffixes,
  225. DoingConfigs,
  226. DoingHints
  227. };
  228. Doing doing = DoingNone;
  229. cmsys::RegularExpression version("^[0-9.]+$");
  230. bool haveVersion = false;
  231. std::set<unsigned int> configArgs;
  232. std::set<unsigned int> moduleArgs;
  233. for (unsigned int i = 1; i < args.size(); ++i) {
  234. if (args[i] == "QUIET") {
  235. this->Quiet = true;
  236. doing = DoingNone;
  237. } else if (args[i] == "EXACT") {
  238. this->VersionExact = true;
  239. doing = DoingNone;
  240. } else if (args[i] == "MODULE") {
  241. moduleArgs.insert(i);
  242. doing = DoingNone;
  243. } else if (args[i] == "CONFIG") {
  244. configArgs.insert(i);
  245. doing = DoingNone;
  246. } else if (args[i] == "NO_MODULE") {
  247. configArgs.insert(i);
  248. doing = DoingNone;
  249. } else if (args[i] == "REQUIRED") {
  250. this->Required = true;
  251. doing = DoingComponents;
  252. } else if (args[i] == "COMPONENTS") {
  253. doing = DoingComponents;
  254. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  255. doing = DoingOptionalComponents;
  256. } else if (args[i] == "NAMES") {
  257. configArgs.insert(i);
  258. doing = DoingNames;
  259. } else if (args[i] == "PATHS") {
  260. configArgs.insert(i);
  261. doing = DoingPaths;
  262. } else if (args[i] == "HINTS") {
  263. configArgs.insert(i);
  264. doing = DoingHints;
  265. } else if (args[i] == "PATH_SUFFIXES") {
  266. configArgs.insert(i);
  267. doing = DoingPathSuffixes;
  268. } else if (args[i] == "CONFIGS") {
  269. configArgs.insert(i);
  270. doing = DoingConfigs;
  271. } else if (args[i] == "NO_POLICY_SCOPE") {
  272. this->PolicyScope = false;
  273. doing = DoingNone;
  274. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  275. this->NoUserRegistry = true;
  276. configArgs.insert(i);
  277. doing = DoingNone;
  278. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  279. this->NoSystemRegistry = true;
  280. configArgs.insert(i);
  281. doing = DoingNone;
  282. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  283. // Ignore legacy option.
  284. configArgs.insert(i);
  285. doing = DoingNone;
  286. } else if (this->CheckCommonArgument(args[i])) {
  287. configArgs.insert(i);
  288. doing = DoingNone;
  289. } else if ((doing == DoingComponents) ||
  290. (doing == DoingOptionalComponents)) {
  291. // Set a variable telling the find script whether this component
  292. // is required.
  293. const char* isRequired = "1";
  294. if (doing == DoingOptionalComponents) {
  295. isRequired = "0";
  296. optionalComponents.insert(args[i]);
  297. } else {
  298. requiredComponents.insert(args[i]);
  299. }
  300. std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
  301. this->AddFindDefinition(req_var, isRequired);
  302. // Append to the list of required components.
  303. components += components_sep;
  304. components += args[i];
  305. components_sep = ";";
  306. } else if (doing == DoingNames) {
  307. this->Names.push_back(args[i]);
  308. } else if (doing == DoingPaths) {
  309. this->UserGuessArgs.push_back(args[i]);
  310. } else if (doing == DoingHints) {
  311. this->UserHintsArgs.push_back(args[i]);
  312. } else if (doing == DoingPathSuffixes) {
  313. this->AddPathSuffix(args[i]);
  314. } else if (doing == DoingConfigs) {
  315. if (args[i].find_first_of(":/\\") != std::string::npos ||
  316. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  317. this->SetError(cmStrCat(
  318. "given CONFIGS option followed by invalid file name \"", args[i],
  319. "\". The names given must be file names without "
  320. "a path and with a \".cmake\" extension."));
  321. return false;
  322. }
  323. this->Configs.push_back(args[i]);
  324. } else if (!haveVersion && version.find(args[i])) {
  325. haveVersion = true;
  326. this->Version = args[i];
  327. } else {
  328. this->SetError(
  329. cmStrCat("called with invalid argument \"", args[i], "\""));
  330. return false;
  331. }
  332. }
  333. std::vector<std::string> doubledComponents;
  334. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  335. optionalComponents.begin(), optionalComponents.end(),
  336. std::back_inserter(doubledComponents));
  337. if (!doubledComponents.empty()) {
  338. this->SetError(
  339. cmStrCat("called with components that are both required and "
  340. "optional:\n",
  341. cmWrap(" ", doubledComponents, "", "\n"), "\n"));
  342. return false;
  343. }
  344. // Maybe choose one mode exclusively.
  345. this->UseFindModules = configArgs.empty();
  346. this->UseConfigFiles = moduleArgs.empty();
  347. if (!this->UseFindModules && !this->UseConfigFiles) {
  348. std::ostringstream e;
  349. e << "given options exclusive to Module mode:\n";
  350. for (unsigned int si : moduleArgs) {
  351. e << " " << args[si] << "\n";
  352. }
  353. e << "and options exclusive to Config mode:\n";
  354. for (unsigned int si : configArgs) {
  355. e << " " << args[si] << "\n";
  356. }
  357. e << "The options are incompatible.";
  358. this->SetError(e.str());
  359. return false;
  360. }
  361. // Ignore EXACT with no version.
  362. if (this->Version.empty() && this->VersionExact) {
  363. this->VersionExact = false;
  364. this->Makefile->IssueMessage(
  365. MessageType::AUTHOR_WARNING,
  366. "Ignoring EXACT since no version is requested.");
  367. }
  368. if (this->Version.empty() || components.empty()) {
  369. // Check whether we are recursing inside "Find<name>.cmake" within
  370. // another find_package(<name>) call.
  371. std::string mod = cmStrCat(this->Name, "_FIND_MODULE");
  372. if (this->Makefile->IsOn(mod)) {
  373. if (this->Version.empty()) {
  374. // Get version information from the outer call if necessary.
  375. // Requested version string.
  376. std::string ver = cmStrCat(this->Name, "_FIND_VERSION");
  377. this->Version = this->Makefile->GetSafeDefinition(ver);
  378. // Whether an exact version is required.
  379. std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  380. this->VersionExact = this->Makefile->IsOn(exact);
  381. }
  382. if (components.empty()) {
  383. std::string components_var = this->Name + "_FIND_COMPONENTS";
  384. components = this->Makefile->GetSafeDefinition(components_var);
  385. }
  386. }
  387. }
  388. if (!this->Version.empty()) {
  389. // Try to parse the version number and store the results that were
  390. // successfully parsed.
  391. unsigned int parsed_major;
  392. unsigned int parsed_minor;
  393. unsigned int parsed_patch;
  394. unsigned int parsed_tweak;
  395. this->VersionCount =
  396. sscanf(this->Version.c_str(), "%u.%u.%u.%u", &parsed_major,
  397. &parsed_minor, &parsed_patch, &parsed_tweak);
  398. switch (this->VersionCount) {
  399. case 4:
  400. this->VersionTweak = parsed_tweak;
  401. CM_FALLTHROUGH;
  402. case 3:
  403. this->VersionPatch = parsed_patch;
  404. CM_FALLTHROUGH;
  405. case 2:
  406. this->VersionMinor = parsed_minor;
  407. CM_FALLTHROUGH;
  408. case 1:
  409. this->VersionMajor = parsed_major;
  410. CM_FALLTHROUGH;
  411. default:
  412. break;
  413. }
  414. }
  415. std::string disableFindPackageVar =
  416. cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
  417. if (this->Makefile->IsOn(disableFindPackageVar)) {
  418. if (this->Required) {
  419. this->SetError(
  420. cmStrCat("for module ", this->Name, " called with REQUIRED, but ",
  421. disableFindPackageVar,
  422. " is enabled. A REQUIRED package cannot be disabled."));
  423. return false;
  424. }
  425. return true;
  426. }
  427. {
  428. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  429. this->Makefile->FindPackageRootPathStack.emplace_back();
  430. std::vector<std::string>& rootPaths =
  431. this->Makefile->FindPackageRootPathStack.back();
  432. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  433. // subject to CMP0074.
  434. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  435. case cmPolicies::WARN:
  436. this->Makefile->MaybeWarnCMP0074(this->Name);
  437. CM_FALLTHROUGH;
  438. case cmPolicies::OLD:
  439. // OLD behavior is to ignore the <pkg>_ROOT variables.
  440. break;
  441. case cmPolicies::REQUIRED_IF_USED:
  442. case cmPolicies::REQUIRED_ALWAYS:
  443. this->Makefile->IssueMessage(
  444. MessageType::FATAL_ERROR,
  445. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  446. break;
  447. case cmPolicies::NEW: {
  448. // NEW behavior is to honor the <pkg>_ROOT variables.
  449. std::string const rootVar = this->Name + "_ROOT";
  450. if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) {
  451. cmExpandList(pkgRoot, rootPaths, false);
  452. }
  453. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  454. } break;
  455. }
  456. }
  457. this->SetModuleVariables(components);
  458. // See if there is a Find<PackageName>.cmake module.
  459. bool loadedPackage = false;
  460. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  461. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  462. loadedPackage = true;
  463. } else {
  464. if (this->FindPackageUsingModuleMode()) {
  465. loadedPackage = true;
  466. } else {
  467. // The package was not loaded. Report errors.
  468. if (HandlePackageMode(HandlePackageModeType::Module)) {
  469. loadedPackage = true;
  470. }
  471. }
  472. }
  473. } else {
  474. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  475. loadedPackage = true;
  476. } else {
  477. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  478. // implicitly assumed)
  479. if (this->UseFindModules && this->UseConfigFiles &&
  480. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  481. std::ostringstream aw;
  482. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  483. aw << "find_package called without either MODULE or CONFIG option "
  484. "and "
  485. "no Find"
  486. << this->Name
  487. << ".cmake module is in CMAKE_MODULE_PATH. "
  488. "Add MODULE to exclusively request Module mode and fail if "
  489. "Find"
  490. << this->Name
  491. << ".cmake is missing. "
  492. "Add CONFIG to exclusively request Config mode and search for "
  493. "a "
  494. "package configuration file provided by "
  495. << this->Name << " (" << this->Name << "Config.cmake or "
  496. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  497. } else {
  498. aw << "find_package called without NO_MODULE option and no "
  499. "Find"
  500. << this->Name
  501. << ".cmake module is in CMAKE_MODULE_PATH. "
  502. "Add NO_MODULE to exclusively request Config mode and search "
  503. "for a "
  504. "package configuration file provided by "
  505. << this->Name << " (" << this->Name << "Config.cmake or "
  506. << cmSystemTools::LowerCase(this->Name)
  507. << "-config.cmake). "
  508. "Otherwise make Find"
  509. << this->Name
  510. << ".cmake available in "
  511. "CMAKE_MODULE_PATH.";
  512. }
  513. aw << "\n"
  514. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  515. "warning.)";
  516. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  517. }
  518. if (this->FindPackageUsingConfigMode()) {
  519. loadedPackage = true;
  520. }
  521. }
  522. }
  523. this->AppendSuccessInformation();
  524. return loadedPackage;
  525. }
  526. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  527. {
  528. bool foundModule = false;
  529. if (!this->FindModule(foundModule)) {
  530. return false;
  531. }
  532. return foundModule;
  533. }
  534. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  535. {
  536. this->Variable = cmStrCat(this->Name, "_DIR");
  537. // Add the default name.
  538. if (this->Names.empty()) {
  539. this->Names.push_back(this->Name);
  540. }
  541. // Add the default configs.
  542. if (this->Configs.empty()) {
  543. for (std::string const& n : this->Names) {
  544. std::string config = cmStrCat(n, "Config.cmake");
  545. this->Configs.push_back(config);
  546. config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
  547. this->Configs.push_back(std::move(config));
  548. }
  549. }
  550. // get igonored paths from vars and reroot them.
  551. std::vector<std::string> ignored;
  552. this->GetIgnoredPaths(ignored);
  553. this->RerootPaths(ignored);
  554. // Construct a set of ignored paths
  555. this->IgnoredPaths.clear();
  556. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  557. // Find and load the package.
  558. return this->HandlePackageMode(HandlePackageModeType::Config);
  559. }
  560. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  561. {
  562. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
  563. // Store the list of components.
  564. std::string components_var = this->Name + "_FIND_COMPONENTS";
  565. this->AddFindDefinition(components_var, components.c_str());
  566. if (this->Quiet) {
  567. // Tell the module that is about to be read that it should find
  568. // quietly.
  569. std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
  570. this->AddFindDefinition(quietly, "1");
  571. }
  572. if (this->Required) {
  573. // Tell the module that is about to be read that it should report
  574. // a fatal error if the package is not found.
  575. std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
  576. this->AddFindDefinition(req, "1");
  577. }
  578. if (!this->Version.empty()) {
  579. // Tell the module that is about to be read what version of the
  580. // package has been requested.
  581. std::string ver = cmStrCat(this->Name, "_FIND_VERSION");
  582. this->AddFindDefinition(ver, this->Version.c_str());
  583. char buf[64];
  584. sprintf(buf, "%u", this->VersionMajor);
  585. this->AddFindDefinition(ver + "_MAJOR", buf);
  586. sprintf(buf, "%u", this->VersionMinor);
  587. this->AddFindDefinition(ver + "_MINOR", buf);
  588. sprintf(buf, "%u", this->VersionPatch);
  589. this->AddFindDefinition(ver + "_PATCH", buf);
  590. sprintf(buf, "%u", this->VersionTweak);
  591. this->AddFindDefinition(ver + "_TWEAK", buf);
  592. sprintf(buf, "%u", this->VersionCount);
  593. this->AddFindDefinition(ver + "_COUNT", buf);
  594. // Tell the module whether an exact version has been requested.
  595. std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  596. this->AddFindDefinition(exact, this->VersionExact ? "1" : "0");
  597. }
  598. }
  599. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  600. const char* val)
  601. {
  602. if (const char* old = this->Makefile->GetDefinition(var)) {
  603. this->OriginalDefs[var].exists = true;
  604. this->OriginalDefs[var].value = old;
  605. } else {
  606. this->OriginalDefs[var].exists = false;
  607. }
  608. if (val) {
  609. this->Makefile->AddDefinition(var, val);
  610. }
  611. }
  612. void cmFindPackageCommand::RestoreFindDefinitions()
  613. {
  614. for (auto const& i : this->OriginalDefs) {
  615. OriginalDef const& od = i.second;
  616. if (od.exists) {
  617. this->Makefile->AddDefinition(i.first, od.value);
  618. } else {
  619. this->Makefile->RemoveDefinition(i.first);
  620. }
  621. }
  622. }
  623. bool cmFindPackageCommand::FindModule(bool& found)
  624. {
  625. std::string module = cmStrCat("Find", this->Name, ".cmake");
  626. bool system = false;
  627. std::string mfile = this->Makefile->GetModulesFile(module, system);
  628. if (!mfile.empty()) {
  629. if (system) {
  630. auto it = this->DeprecatedFindModules.find(this->Name);
  631. if (it != this->DeprecatedFindModules.end()) {
  632. cmPolicies::PolicyStatus status =
  633. this->Makefile->GetPolicyStatus(it->second);
  634. switch (status) {
  635. case cmPolicies::WARN: {
  636. this->Makefile->IssueMessage(
  637. MessageType::AUTHOR_WARNING,
  638. cmStrCat(cmPolicies::GetPolicyWarning(it->second), "\n"));
  639. CM_FALLTHROUGH;
  640. }
  641. case cmPolicies::OLD:
  642. break;
  643. case cmPolicies::REQUIRED_IF_USED:
  644. case cmPolicies::REQUIRED_ALWAYS:
  645. case cmPolicies::NEW:
  646. return true;
  647. }
  648. }
  649. }
  650. // Load the module we found, and set "<name>_FIND_MODULE" to true
  651. // while inside it.
  652. found = true;
  653. std::string var = cmStrCat(this->Name, "_FIND_MODULE");
  654. this->Makefile->AddDefinition(var, "1");
  655. bool result = this->ReadListFile(mfile, DoPolicyScope);
  656. this->Makefile->RemoveDefinition(var);
  657. return result;
  658. }
  659. return true;
  660. }
  661. bool cmFindPackageCommand::HandlePackageMode(
  662. HandlePackageModeType handlePackageModeType)
  663. {
  664. this->ConsideredConfigs.clear();
  665. // Try to find the config file.
  666. const char* def = this->Makefile->GetDefinition(this->Variable);
  667. // Try to load the config file if the directory is known
  668. bool fileFound = false;
  669. if (this->UseConfigFiles) {
  670. if (!cmIsOff(def)) {
  671. // Get the directory from the variable value.
  672. std::string dir = def;
  673. cmSystemTools::ConvertToUnixSlashes(dir);
  674. // Treat relative paths with respect to the current source dir.
  675. if (!cmSystemTools::FileIsFullPath(dir)) {
  676. dir = "/" + dir;
  677. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  678. }
  679. // The file location was cached. Look for the correct file.
  680. std::string file;
  681. if (this->FindConfigFile(dir, file)) {
  682. this->FileFound = file;
  683. fileFound = true;
  684. }
  685. def = this->Makefile->GetDefinition(this->Variable);
  686. }
  687. // Search for the config file if it is not already found.
  688. if (cmIsOff(def) || !fileFound) {
  689. fileFound = this->FindConfig();
  690. }
  691. // Sanity check.
  692. if (fileFound && this->FileFound.empty()) {
  693. this->Makefile->IssueMessage(
  694. MessageType::INTERNAL_ERROR,
  695. "fileFound is true but FileFound is empty!");
  696. fileFound = false;
  697. }
  698. }
  699. std::string foundVar = cmStrCat(this->Name, "_FOUND");
  700. std::string notFoundMessageVar = cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
  701. std::string notFoundMessage;
  702. // If the directory for the config file was found, try to read the file.
  703. bool result = true;
  704. bool found = false;
  705. bool configFileSetFOUNDFalse = false;
  706. if (fileFound) {
  707. if (this->Makefile->IsDefinitionSet(foundVar) &&
  708. !this->Makefile->IsOn(foundVar)) {
  709. // by removing Foo_FOUND here if it is FALSE, we don't really change
  710. // the situation for the Config file which is about to be included,
  711. // but we make it possible to detect later on whether the Config file
  712. // has set Foo_FOUND to FALSE itself:
  713. this->Makefile->RemoveDefinition(foundVar);
  714. }
  715. this->Makefile->RemoveDefinition(notFoundMessageVar);
  716. // Set the version variables before loading the config file.
  717. // It may override them.
  718. this->StoreVersionFound();
  719. // Parse the configuration file.
  720. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  721. // The package has been found.
  722. found = true;
  723. // Check whether the Config file has set Foo_FOUND to FALSE:
  724. if (this->Makefile->IsDefinitionSet(foundVar) &&
  725. !this->Makefile->IsOn(foundVar)) {
  726. // we get here if the Config file has set Foo_FOUND actively to FALSE
  727. found = false;
  728. configFileSetFOUNDFalse = true;
  729. notFoundMessage =
  730. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  731. }
  732. } else {
  733. // The configuration file is invalid.
  734. result = false;
  735. }
  736. }
  737. if (this->UseFindModules && !found &&
  738. handlePackageModeType == HandlePackageModeType::Config &&
  739. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  740. // Config mode failed. Allow Module case.
  741. result = false;
  742. }
  743. // package not found
  744. if (result && !found) {
  745. // warn if package required or neither quiet nor in config mode
  746. if (this->Required ||
  747. !(this->Quiet ||
  748. (this->UseConfigFiles && !this->UseFindModules &&
  749. this->ConsideredConfigs.empty()))) {
  750. // The variable is not set.
  751. std::ostringstream e;
  752. std::ostringstream aw;
  753. if (configFileSetFOUNDFalse) {
  754. /* clang-format off */
  755. e << "Found package configuration file:\n"
  756. " " << this->FileFound << "\n"
  757. "but it set " << foundVar << " to FALSE so package \"" <<
  758. this->Name << "\" is considered to be NOT FOUND.";
  759. /* clang-format on */
  760. if (!notFoundMessage.empty()) {
  761. e << " Reason given by package: \n" << notFoundMessage << "\n";
  762. }
  763. }
  764. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  765. // have been found, but they didn't have appropriate versions.
  766. else if (!this->ConsideredConfigs.empty()) {
  767. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  768. e << "Could not find a configuration file for package \"" << this->Name
  769. << "\" that "
  770. << (this->VersionExact ? "exactly matches" : "is compatible with")
  771. << " requested version \"" << this->Version << "\".\n"
  772. << "The following configuration files were considered but not "
  773. "accepted:\n";
  774. for (ConfigFileInfo const& info :
  775. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  776. e << " " << info.filename << ", version: " << info.version << "\n";
  777. }
  778. } else {
  779. std::string requestedVersionString;
  780. if (!this->Version.empty()) {
  781. requestedVersionString =
  782. cmStrCat(" (requested version ", this->Version, ')');
  783. }
  784. if (this->UseConfigFiles) {
  785. if (this->UseFindModules) {
  786. e << "By not providing \"Find" << this->Name
  787. << ".cmake\" in "
  788. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  789. "package configuration file provided by \""
  790. << this->Name
  791. << "\", "
  792. "but CMake did not find one.\n";
  793. }
  794. if (this->Configs.size() == 1) {
  795. e << "Could not find a package configuration file named \""
  796. << this->Configs[0] << "\" provided by package \"" << this->Name
  797. << "\"" << requestedVersionString << ".\n";
  798. } else {
  799. e << "Could not find a package configuration file provided by \""
  800. << this->Name << "\"" << requestedVersionString
  801. << " with any of the following names:\n"
  802. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  803. }
  804. e << "Add the installation prefix of \"" << this->Name
  805. << "\" to "
  806. "CMAKE_PREFIX_PATH or set \""
  807. << this->Variable
  808. << "\" to a "
  809. "directory containing one of the above files. "
  810. "If \""
  811. << this->Name
  812. << "\" provides a separate development "
  813. "package or SDK, be sure it has been installed.";
  814. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  815. {
  816. e << "No \"Find" << this->Name << ".cmake\" found in "
  817. << "CMAKE_MODULE_PATH.";
  818. aw
  819. << "Find" << this->Name
  820. << ".cmake must either be part of this "
  821. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  822. "it points to the correct location inside its source tree.\n"
  823. "Or it must be installed by a package which has already been "
  824. "found via find_package(). In this case make sure that "
  825. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  826. "contain the location where that package has installed "
  827. "Find"
  828. << this->Name
  829. << ".cmake. This must be a location "
  830. "provided by that package. This error in general means that "
  831. "the buildsystem of this project is relying on a Find-module "
  832. "without ensuring that it is actually available.\n";
  833. }
  834. }
  835. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  836. : MessageType::WARNING,
  837. e.str());
  838. if (this->Required) {
  839. cmSystemTools::SetFatalErrorOccured();
  840. }
  841. if (!aw.str().empty()) {
  842. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  843. }
  844. }
  845. // output result if in config mode but not in quiet mode
  846. else if (!this->Quiet) {
  847. this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
  848. " (missing: ", this->Name,
  849. "_DIR)"),
  850. -1);
  851. }
  852. }
  853. // Set a variable marking whether the package was found.
  854. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  855. // Set a variable naming the configuration file that was found.
  856. std::string fileVar = cmStrCat(this->Name, "_CONFIG");
  857. if (found) {
  858. this->Makefile->AddDefinition(fileVar, this->FileFound);
  859. } else {
  860. this->Makefile->RemoveDefinition(fileVar);
  861. }
  862. std::string consideredConfigsVar =
  863. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  864. std::string consideredVersionsVar =
  865. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  866. std::string consideredConfigFiles;
  867. std::string consideredVersions;
  868. const char* sep = "";
  869. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  870. consideredConfigFiles += sep;
  871. consideredVersions += sep;
  872. consideredConfigFiles += i.filename;
  873. consideredVersions += i.version;
  874. sep = ";";
  875. }
  876. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  877. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  878. return result;
  879. }
  880. bool cmFindPackageCommand::FindConfig()
  881. {
  882. // Compute the set of search prefixes.
  883. this->ComputePrefixes();
  884. // Look for the project's configuration file.
  885. bool found = false;
  886. // Search for frameworks.
  887. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  888. found = this->FindFrameworkConfig();
  889. }
  890. // Search for apps.
  891. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  892. found = this->FindAppBundleConfig();
  893. }
  894. // Search prefixes.
  895. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  896. found = this->FindPrefixedConfig();
  897. }
  898. // Search for frameworks.
  899. if (!found && this->SearchFrameworkLast) {
  900. found = this->FindFrameworkConfig();
  901. }
  902. // Search for apps.
  903. if (!found && this->SearchAppBundleLast) {
  904. found = this->FindAppBundleConfig();
  905. }
  906. // Store the entry in the cache so it can be set by the user.
  907. std::string init;
  908. if (found) {
  909. init = cmSystemTools::GetFilenamePath(this->FileFound);
  910. } else {
  911. init = this->Variable + "-NOTFOUND";
  912. }
  913. std::string help =
  914. cmStrCat("The directory containing a CMake configuration file for ",
  915. this->Name, '.');
  916. // We force the value since we do not get here if it was already set.
  917. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
  918. help.c_str(), cmStateEnums::PATH, true);
  919. return found;
  920. }
  921. bool cmFindPackageCommand::FindPrefixedConfig()
  922. {
  923. std::vector<std::string> const& prefixes = this->SearchPaths;
  924. for (std::string const& p : prefixes) {
  925. if (this->SearchPrefix(p)) {
  926. return true;
  927. }
  928. }
  929. return false;
  930. }
  931. bool cmFindPackageCommand::FindFrameworkConfig()
  932. {
  933. std::vector<std::string> const& prefixes = this->SearchPaths;
  934. for (std::string const& p : prefixes) {
  935. if (this->SearchFrameworkPrefix(p)) {
  936. return true;
  937. }
  938. }
  939. return false;
  940. }
  941. bool cmFindPackageCommand::FindAppBundleConfig()
  942. {
  943. std::vector<std::string> const& prefixes = this->SearchPaths;
  944. for (std::string const& p : prefixes) {
  945. if (this->SearchAppBundlePrefix(p)) {
  946. return true;
  947. }
  948. }
  949. return false;
  950. }
  951. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  952. PolicyScopeRule psr)
  953. {
  954. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  955. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  956. return true;
  957. }
  958. std::string e = cmStrCat("Error reading CMake code from \"", f, "\".");
  959. this->SetError(e);
  960. return false;
  961. }
  962. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  963. {
  964. std::vector<std::string> foundContents;
  965. const char* foundProp =
  966. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  967. if (foundProp && *foundProp) {
  968. std::string tmp = foundProp;
  969. cmExpandList(tmp, foundContents, false);
  970. auto nameIt =
  971. std::find(foundContents.begin(), foundContents.end(), this->Name);
  972. if (nameIt != foundContents.end()) {
  973. foundContents.erase(nameIt);
  974. }
  975. }
  976. std::vector<std::string> notFoundContents;
  977. const char* notFoundProp =
  978. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  979. if (notFoundProp && *notFoundProp) {
  980. std::string tmp = notFoundProp;
  981. cmExpandList(tmp, notFoundContents, false);
  982. auto nameIt =
  983. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  984. if (nameIt != notFoundContents.end()) {
  985. notFoundContents.erase(nameIt);
  986. }
  987. }
  988. if (found) {
  989. foundContents.push_back(this->Name);
  990. } else {
  991. notFoundContents.push_back(this->Name);
  992. }
  993. std::string tmp = cmJoin(foundContents, ";");
  994. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  995. tmp = cmJoin(notFoundContents, ";");
  996. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  997. tmp.c_str());
  998. }
  999. void cmFindPackageCommand::AppendSuccessInformation()
  1000. {
  1001. {
  1002. std::string transitivePropName =
  1003. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1004. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1005. }
  1006. std::string found = cmStrCat(this->Name, "_FOUND");
  1007. std::string upperFound = cmSystemTools::UpperCase(found);
  1008. const char* upperResult = this->Makefile->GetDefinition(upperFound);
  1009. const char* result = this->Makefile->GetDefinition(found);
  1010. bool packageFound = ((cmIsOn(result)) || (cmIsOn(upperResult)));
  1011. this->AppendToFoundProperty(packageFound);
  1012. // Record whether the find was quiet or not, so this can be used
  1013. // e.g. in FeatureSummary.cmake
  1014. std::string quietInfoPropName = cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1015. this->Makefile->GetState()->SetGlobalProperty(
  1016. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1017. // set a global property to record the required version of this package
  1018. std::string versionInfoPropName =
  1019. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1020. std::string versionInfo;
  1021. if (!this->Version.empty()) {
  1022. versionInfo =
  1023. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1024. }
  1025. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1026. versionInfo.c_str());
  1027. if (this->Required) {
  1028. std::string requiredInfoPropName =
  1029. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1030. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1031. "REQUIRED");
  1032. }
  1033. // Restore original state of "_FIND_" variables we set.
  1034. this->RestoreFindDefinitions();
  1035. // Pop the package stack
  1036. this->Makefile->FindPackageRootPathStack.pop_back();
  1037. }
  1038. void cmFindPackageCommand::ComputePrefixes()
  1039. {
  1040. if (!this->NoDefaultPath) {
  1041. if (!this->NoPackageRootPath) {
  1042. this->FillPrefixesPackageRoot();
  1043. }
  1044. if (!this->NoCMakePath) {
  1045. this->FillPrefixesCMakeVariable();
  1046. }
  1047. if (!this->NoCMakeEnvironmentPath) {
  1048. this->FillPrefixesCMakeEnvironment();
  1049. }
  1050. }
  1051. this->FillPrefixesUserHints();
  1052. if (!this->NoDefaultPath) {
  1053. if (!this->NoSystemEnvironmentPath) {
  1054. this->FillPrefixesSystemEnvironment();
  1055. }
  1056. if (!this->NoUserRegistry) {
  1057. this->FillPrefixesUserRegistry();
  1058. }
  1059. if (!this->NoCMakeSystemPath) {
  1060. this->FillPrefixesCMakeSystemVariable();
  1061. }
  1062. if (!this->NoSystemRegistry) {
  1063. this->FillPrefixesSystemRegistry();
  1064. }
  1065. }
  1066. this->FillPrefixesUserGuess();
  1067. this->ComputeFinalPaths();
  1068. }
  1069. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1070. {
  1071. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1072. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1073. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  1074. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1075. ++pkgPaths) {
  1076. for (std::string const& path : *pkgPaths) {
  1077. paths.AddPath(path);
  1078. }
  1079. }
  1080. }
  1081. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1082. {
  1083. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1084. // Check the environment variable with the same name as the cache
  1085. // entry.
  1086. paths.AddEnvPath(this->Variable);
  1087. // And now the general CMake environment variables
  1088. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1089. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1090. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1091. }
  1092. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1093. {
  1094. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1095. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1096. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1097. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1098. }
  1099. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1100. {
  1101. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1102. // Use the system search path to generate prefixes.
  1103. // Relative paths are interpreted with respect to the current
  1104. // working directory.
  1105. std::vector<std::string> tmp;
  1106. cmSystemTools::GetPath(tmp);
  1107. for (std::string const& i : tmp) {
  1108. // If the path is a PREFIX/bin case then add its parent instead.
  1109. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1110. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1111. } else {
  1112. paths.AddPath(i);
  1113. }
  1114. }
  1115. }
  1116. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1117. {
  1118. #if defined(_WIN32) && !defined(__CYGWIN__)
  1119. this->LoadPackageRegistryWinUser();
  1120. #elif defined(__HAIKU__)
  1121. char dir[B_PATH_NAME_LENGTH];
  1122. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1123. B_OK) {
  1124. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  1125. this->LoadPackageRegistryDir(fname,
  1126. this->LabeledPaths[PathLabel::UserRegistry]);
  1127. }
  1128. #else
  1129. std::string dir;
  1130. if (cmSystemTools::GetEnv("HOME", dir)) {
  1131. dir += "/.cmake/packages/";
  1132. dir += this->Name;
  1133. this->LoadPackageRegistryDir(dir,
  1134. this->LabeledPaths[PathLabel::UserRegistry]);
  1135. }
  1136. #endif
  1137. }
  1138. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1139. {
  1140. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1141. return;
  1142. }
  1143. #if defined(_WIN32) && !defined(__CYGWIN__)
  1144. this->LoadPackageRegistryWinSystem();
  1145. #endif
  1146. }
  1147. #if defined(_WIN32) && !defined(__CYGWIN__)
  1148. # include <windows.h>
  1149. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1150. # if !defined(KEY_WOW64_32KEY)
  1151. # define KEY_WOW64_32KEY 0x0200
  1152. # endif
  1153. # if !defined(KEY_WOW64_64KEY)
  1154. # define KEY_WOW64_64KEY 0x0100
  1155. # endif
  1156. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1157. {
  1158. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1159. this->LoadPackageRegistryWin(true, 0,
  1160. this->LabeledPaths[PathLabel::UserRegistry]);
  1161. }
  1162. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1163. {
  1164. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1165. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1166. // Prefer the target platform view first.
  1167. if (this->Makefile->PlatformIs64Bit()) {
  1168. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1169. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1170. } else {
  1171. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1172. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1173. }
  1174. }
  1175. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1176. cmSearchPath& outPaths)
  1177. {
  1178. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1179. key += cmsys::Encoding::ToWide(this->Name);
  1180. std::set<std::wstring> bad;
  1181. HKEY hKey;
  1182. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1183. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1184. DWORD valueType = REG_NONE;
  1185. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1186. std::vector<wchar_t> data(512);
  1187. bool done = false;
  1188. DWORD index = 0;
  1189. while (!done) {
  1190. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1191. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1192. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1193. (BYTE*)&data[0], &dataSize)) {
  1194. case ERROR_SUCCESS:
  1195. ++index;
  1196. if (valueType == REG_SZ) {
  1197. data[dataSize] = 0;
  1198. if (!this->CheckPackageRegistryEntry(
  1199. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1200. // The entry is invalid.
  1201. bad.insert(name);
  1202. }
  1203. }
  1204. break;
  1205. case ERROR_MORE_DATA:
  1206. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1207. break;
  1208. case ERROR_NO_MORE_ITEMS:
  1209. default:
  1210. done = true;
  1211. break;
  1212. }
  1213. }
  1214. RegCloseKey(hKey);
  1215. }
  1216. // Remove bad values if possible.
  1217. if (user && !bad.empty() &&
  1218. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1219. &hKey) == ERROR_SUCCESS) {
  1220. for (std::wstring const& v : bad) {
  1221. RegDeleteValueW(hKey, v.c_str());
  1222. }
  1223. RegCloseKey(hKey);
  1224. }
  1225. }
  1226. #else
  1227. class cmFindPackageCommandHoldFile
  1228. {
  1229. const char* File;
  1230. public:
  1231. cmFindPackageCommandHoldFile(const char* f)
  1232. : File(f)
  1233. {
  1234. }
  1235. ~cmFindPackageCommandHoldFile()
  1236. {
  1237. if (this->File) {
  1238. cmSystemTools::RemoveFile(this->File);
  1239. }
  1240. }
  1241. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  1242. cmFindPackageCommandHoldFile& operator=(
  1243. const cmFindPackageCommandHoldFile&) = delete;
  1244. void Release() { this->File = nullptr; }
  1245. };
  1246. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1247. cmSearchPath& outPaths)
  1248. {
  1249. cmsys::Directory files;
  1250. if (!files.Load(dir)) {
  1251. return;
  1252. }
  1253. std::string fname;
  1254. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1255. fname = cmStrCat(dir, '/', files.GetFile(i));
  1256. if (!cmSystemTools::FileIsDirectory(fname)) {
  1257. // Hold this file hostage until it behaves.
  1258. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1259. // Load the file.
  1260. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1261. std::string fentry;
  1262. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1263. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1264. // The file references an existing package, so release it.
  1265. holdFile.Release();
  1266. }
  1267. }
  1268. }
  1269. // TODO: Wipe out the directory if it is empty.
  1270. }
  1271. #endif
  1272. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1273. cmSearchPath& outPaths)
  1274. {
  1275. // Parse the content of one package registry entry.
  1276. if (cmSystemTools::FileIsFullPath(fname)) {
  1277. // The first line in the stream is the full path to a file or
  1278. // directory containing the package.
  1279. if (cmSystemTools::FileExists(fname)) {
  1280. // The path exists. Look for the package here.
  1281. if (!cmSystemTools::FileIsDirectory(fname)) {
  1282. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1283. } else {
  1284. outPaths.AddPath(fname);
  1285. }
  1286. return true;
  1287. }
  1288. // The path does not exist. Assume the stream content is
  1289. // associated with an old package that no longer exists, and
  1290. // delete it to keep the package registry clean.
  1291. return false;
  1292. }
  1293. // The first line in the stream is not the full path to a file or
  1294. // directory. Assume the stream content was created by a future
  1295. // version of CMake that uses a different format, and leave it.
  1296. return true;
  1297. }
  1298. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1299. {
  1300. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1301. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1302. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1303. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1304. }
  1305. void cmFindPackageCommand::FillPrefixesUserGuess()
  1306. {
  1307. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1308. for (std::string const& p : this->UserGuessArgs) {
  1309. paths.AddUserPath(p);
  1310. }
  1311. }
  1312. void cmFindPackageCommand::FillPrefixesUserHints()
  1313. {
  1314. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1315. for (std::string const& p : this->UserHintsArgs) {
  1316. paths.AddUserPath(p);
  1317. }
  1318. }
  1319. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1320. {
  1321. assert(!dir.empty() && dir.back() == '/');
  1322. // Check each path suffix on this directory.
  1323. for (std::string const& s : this->SearchPathSuffixes) {
  1324. std::string d = dir;
  1325. if (!s.empty()) {
  1326. d += s;
  1327. d += "/";
  1328. }
  1329. if (this->CheckDirectory(d)) {
  1330. return true;
  1331. }
  1332. }
  1333. return false;
  1334. }
  1335. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1336. {
  1337. assert(!dir.empty() && dir.back() == '/');
  1338. // Look for the file in this directory.
  1339. std::string d = dir.substr(0, dir.size() - 1);
  1340. if (this->FindConfigFile(d, this->FileFound)) {
  1341. // Remove duplicate slashes.
  1342. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1343. return true;
  1344. }
  1345. return false;
  1346. }
  1347. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1348. std::string& file)
  1349. {
  1350. if (this->IgnoredPaths.count(dir)) {
  1351. return false;
  1352. }
  1353. for (std::string const& c : this->Configs) {
  1354. file = cmStrCat(dir, '/', c);
  1355. if (this->DebugMode) {
  1356. fprintf(stderr, "Checking file [%s]\n", file.c_str());
  1357. }
  1358. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1359. // Allow resolving symlinks when the config file is found through a link
  1360. if (this->UseRealPath) {
  1361. file = cmSystemTools::GetRealPath(file);
  1362. }
  1363. return true;
  1364. }
  1365. }
  1366. return false;
  1367. }
  1368. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1369. {
  1370. bool result = false; // by default, assume the version is not ok.
  1371. bool haveResult = false;
  1372. std::string version = "unknown";
  1373. // Get the filename without the .cmake extension.
  1374. std::string::size_type pos = config_file.rfind('.');
  1375. std::string version_file_base = config_file.substr(0, pos);
  1376. // Look for foo-config-version.cmake
  1377. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  1378. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1379. result = this->CheckVersionFile(version_file, version);
  1380. haveResult = true;
  1381. }
  1382. // Look for fooConfigVersion.cmake
  1383. version_file = cmStrCat(version_file_base, "Version.cmake");
  1384. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1385. result = this->CheckVersionFile(version_file, version);
  1386. haveResult = true;
  1387. }
  1388. // If no version was requested a versionless package is acceptable.
  1389. if (!haveResult && this->Version.empty()) {
  1390. result = true;
  1391. }
  1392. ConfigFileInfo configFileInfo;
  1393. configFileInfo.filename = config_file;
  1394. configFileInfo.version = version;
  1395. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1396. return result;
  1397. }
  1398. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1399. std::string& result_version)
  1400. {
  1401. // The version file will be loaded in an isolated scope.
  1402. cmMakefile::ScopePushPop varScope(this->Makefile);
  1403. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1404. static_cast<void>(varScope);
  1405. static_cast<void>(polScope);
  1406. // Clear the output variables.
  1407. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1408. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1409. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1410. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1411. // Set the input variables.
  1412. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  1413. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION", this->Version);
  1414. char buf[64];
  1415. sprintf(buf, "%u", this->VersionMajor);
  1416. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
  1417. sprintf(buf, "%u", this->VersionMinor);
  1418. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
  1419. sprintf(buf, "%u", this->VersionPatch);
  1420. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
  1421. sprintf(buf, "%u", this->VersionTweak);
  1422. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
  1423. sprintf(buf, "%u", this->VersionCount);
  1424. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
  1425. // Load the version check file. Pass NoPolicyScope because we do
  1426. // our own policy push/pop independent of CMP0011.
  1427. bool suitable = false;
  1428. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1429. // Check the output variables.
  1430. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1431. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1432. if (!okay && !this->VersionExact) {
  1433. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1434. }
  1435. // The package is suitable if the version is okay and not
  1436. // explicitly unsuitable.
  1437. suitable = !unsuitable && (okay || this->Version.empty());
  1438. if (suitable) {
  1439. // Get the version found.
  1440. this->VersionFound =
  1441. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1442. // Try to parse the version number and store the results that were
  1443. // successfully parsed.
  1444. unsigned int parsed_major;
  1445. unsigned int parsed_minor;
  1446. unsigned int parsed_patch;
  1447. unsigned int parsed_tweak;
  1448. this->VersionFoundCount =
  1449. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1450. &parsed_minor, &parsed_patch, &parsed_tweak);
  1451. switch (this->VersionFoundCount) {
  1452. case 4:
  1453. this->VersionFoundTweak = parsed_tweak;
  1454. CM_FALLTHROUGH;
  1455. case 3:
  1456. this->VersionFoundPatch = parsed_patch;
  1457. CM_FALLTHROUGH;
  1458. case 2:
  1459. this->VersionFoundMinor = parsed_minor;
  1460. CM_FALLTHROUGH;
  1461. case 1:
  1462. this->VersionFoundMajor = parsed_major;
  1463. CM_FALLTHROUGH;
  1464. default:
  1465. break;
  1466. }
  1467. }
  1468. }
  1469. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1470. if (result_version.empty()) {
  1471. result_version = "unknown";
  1472. }
  1473. // Succeed if the version is suitable.
  1474. return suitable;
  1475. }
  1476. void cmFindPackageCommand::StoreVersionFound()
  1477. {
  1478. // Store the whole version string.
  1479. std::string ver = cmStrCat(this->Name, "_VERSION");
  1480. if (this->VersionFound.empty()) {
  1481. this->Makefile->RemoveDefinition(ver);
  1482. } else {
  1483. this->Makefile->AddDefinition(ver, this->VersionFound);
  1484. }
  1485. // Store the version components.
  1486. char buf[64];
  1487. sprintf(buf, "%u", this->VersionFoundMajor);
  1488. this->Makefile->AddDefinition(ver + "_MAJOR", buf);
  1489. sprintf(buf, "%u", this->VersionFoundMinor);
  1490. this->Makefile->AddDefinition(ver + "_MINOR", buf);
  1491. sprintf(buf, "%u", this->VersionFoundPatch);
  1492. this->Makefile->AddDefinition(ver + "_PATCH", buf);
  1493. sprintf(buf, "%u", this->VersionFoundTweak);
  1494. this->Makefile->AddDefinition(ver + "_TWEAK", buf);
  1495. sprintf(buf, "%u", this->VersionFoundCount);
  1496. this->Makefile->AddDefinition(ver + "_COUNT", buf);
  1497. }
  1498. class cmFileListGeneratorBase
  1499. {
  1500. public:
  1501. virtual ~cmFileListGeneratorBase() = default;
  1502. protected:
  1503. bool Consider(std::string const& fullPath, cmFileList& listing);
  1504. private:
  1505. bool Search(cmFileList&);
  1506. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1507. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1508. friend class cmFileList;
  1509. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1510. std::unique_ptr<cmFileListGeneratorBase> Next;
  1511. };
  1512. class cmFileList
  1513. {
  1514. public:
  1515. virtual ~cmFileList() = default;
  1516. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1517. {
  1518. if (this->Last) {
  1519. this->Last = this->Last->SetNext(rhs);
  1520. } else {
  1521. this->First = rhs.Clone();
  1522. this->Last = this->First.get();
  1523. }
  1524. return *this;
  1525. }
  1526. bool Search()
  1527. {
  1528. if (this->First) {
  1529. return this->First->Search(*this);
  1530. }
  1531. return false;
  1532. }
  1533. private:
  1534. virtual bool Visit(std::string const& fullPath) = 0;
  1535. friend class cmFileListGeneratorBase;
  1536. std::unique_ptr<cmFileListGeneratorBase> First;
  1537. cmFileListGeneratorBase* Last = nullptr;
  1538. };
  1539. class cmFindPackageFileList : public cmFileList
  1540. {
  1541. public:
  1542. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1543. : FPC(fpc)
  1544. , UseSuffixes(use_suffixes)
  1545. {
  1546. }
  1547. private:
  1548. bool Visit(std::string const& fullPath) override
  1549. {
  1550. if (this->UseSuffixes) {
  1551. return this->FPC->SearchDirectory(fullPath);
  1552. }
  1553. return this->FPC->CheckDirectory(fullPath);
  1554. }
  1555. cmFindPackageCommand* FPC;
  1556. bool UseSuffixes;
  1557. };
  1558. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1559. {
  1560. return this->Search("", listing);
  1561. }
  1562. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1563. cmFileListGeneratorBase const& next)
  1564. {
  1565. this->Next = next.Clone();
  1566. return this->Next.get();
  1567. }
  1568. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1569. cmFileList& listing)
  1570. {
  1571. if (this->Next) {
  1572. return this->Next->Search(fullPath + "/", listing);
  1573. }
  1574. return listing.Visit(fullPath + "/");
  1575. }
  1576. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1577. {
  1578. public:
  1579. cmFileListGeneratorFixed(std::string str)
  1580. : String(std::move(str))
  1581. {
  1582. }
  1583. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1584. : String(r.String)
  1585. {
  1586. }
  1587. private:
  1588. std::string String;
  1589. bool Search(std::string const& parent, cmFileList& lister) override
  1590. {
  1591. std::string fullPath = parent + this->String;
  1592. return this->Consider(fullPath, lister);
  1593. }
  1594. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1595. {
  1596. std::unique_ptr<cmFileListGeneratorBase> g(
  1597. new cmFileListGeneratorFixed(*this));
  1598. return g;
  1599. }
  1600. };
  1601. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1602. {
  1603. public:
  1604. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1605. : Vector(v)
  1606. {
  1607. }
  1608. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1609. : Vector(r.Vector)
  1610. {
  1611. }
  1612. private:
  1613. std::vector<std::string> const& Vector;
  1614. bool Search(std::string const& parent, cmFileList& lister) override
  1615. {
  1616. for (std::string const& i : this->Vector) {
  1617. if (this->Consider(parent + i, lister)) {
  1618. return true;
  1619. }
  1620. }
  1621. return false;
  1622. }
  1623. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1624. {
  1625. std::unique_ptr<cmFileListGeneratorBase> g(
  1626. new cmFileListGeneratorEnumerate(*this));
  1627. return g;
  1628. }
  1629. };
  1630. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1631. {
  1632. public:
  1633. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1634. cmFindPackageCommand::SortOrderType so,
  1635. cmFindPackageCommand::SortDirectionType sd)
  1636. : Names(names)
  1637. {
  1638. this->SetSort(so, sd);
  1639. }
  1640. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1641. : Names(r.Names)
  1642. {
  1643. this->SetSort(r.SortOrder, r.SortDirection);
  1644. }
  1645. void SetSort(cmFindPackageCommand::SortOrderType o,
  1646. cmFindPackageCommand::SortDirectionType d)
  1647. {
  1648. SortOrder = o;
  1649. SortDirection = d;
  1650. }
  1651. protected:
  1652. // sort parameters
  1653. cmFindPackageCommand::SortOrderType SortOrder;
  1654. cmFindPackageCommand::SortDirectionType SortDirection;
  1655. private:
  1656. std::vector<std::string> const& Names;
  1657. bool Search(std::string const& parent, cmFileList& lister) override
  1658. {
  1659. // Construct a list of matches.
  1660. std::vector<std::string> matches;
  1661. cmsys::Directory d;
  1662. d.Load(parent);
  1663. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1664. const char* fname = d.GetFile(i);
  1665. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1666. continue;
  1667. }
  1668. for (std::string const& n : this->Names) {
  1669. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1670. matches.emplace_back(fname);
  1671. }
  1672. }
  1673. }
  1674. // before testing the matches check if there is a specific sorting order to
  1675. // perform
  1676. if (this->SortOrder != cmFindPackageCommand::None) {
  1677. cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
  1678. SortDirection);
  1679. }
  1680. for (std::string const& i : matches) {
  1681. if (this->Consider(parent + i, lister)) {
  1682. return true;
  1683. }
  1684. }
  1685. return false;
  1686. }
  1687. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1688. {
  1689. std::unique_ptr<cmFileListGeneratorBase> g(
  1690. new cmFileListGeneratorProject(*this));
  1691. return g;
  1692. }
  1693. };
  1694. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1695. {
  1696. public:
  1697. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1698. const char* ext)
  1699. : Names(names)
  1700. , Extension(ext)
  1701. {
  1702. }
  1703. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1704. : Names(r.Names)
  1705. , Extension(r.Extension)
  1706. {
  1707. }
  1708. private:
  1709. std::vector<std::string> const& Names;
  1710. std::string Extension;
  1711. bool Search(std::string const& parent, cmFileList& lister) override
  1712. {
  1713. // Construct a list of matches.
  1714. std::vector<std::string> matches;
  1715. cmsys::Directory d;
  1716. d.Load(parent);
  1717. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1718. const char* fname = d.GetFile(i);
  1719. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1720. continue;
  1721. }
  1722. for (std::string name : this->Names) {
  1723. name += this->Extension;
  1724. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1725. matches.emplace_back(fname);
  1726. }
  1727. }
  1728. }
  1729. for (std::string const& i : matches) {
  1730. if (this->Consider(parent + i, lister)) {
  1731. return true;
  1732. }
  1733. }
  1734. return false;
  1735. }
  1736. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1737. {
  1738. std::unique_ptr<cmFileListGeneratorBase> g(
  1739. new cmFileListGeneratorMacProject(*this));
  1740. return g;
  1741. }
  1742. };
  1743. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1744. {
  1745. public:
  1746. cmFileListGeneratorCaseInsensitive(std::string str)
  1747. : String(std::move(str))
  1748. {
  1749. }
  1750. cmFileListGeneratorCaseInsensitive(
  1751. cmFileListGeneratorCaseInsensitive const& r)
  1752. : String(r.String)
  1753. {
  1754. }
  1755. private:
  1756. std::string String;
  1757. bool Search(std::string const& parent, cmFileList& lister) override
  1758. {
  1759. // Look for matching files.
  1760. std::vector<std::string> matches;
  1761. cmsys::Directory d;
  1762. d.Load(parent);
  1763. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1764. const char* fname = d.GetFile(i);
  1765. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1766. continue;
  1767. }
  1768. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1769. if (this->Consider(parent + fname, lister)) {
  1770. return true;
  1771. }
  1772. }
  1773. }
  1774. return false;
  1775. }
  1776. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1777. {
  1778. std::unique_ptr<cmFileListGeneratorBase> g(
  1779. new cmFileListGeneratorCaseInsensitive(*this));
  1780. return g;
  1781. }
  1782. };
  1783. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  1784. {
  1785. public:
  1786. cmFileListGeneratorGlob(std::string str)
  1787. : Pattern(std::move(str))
  1788. {
  1789. }
  1790. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  1791. : Pattern(r.Pattern)
  1792. {
  1793. }
  1794. private:
  1795. std::string Pattern;
  1796. bool Search(std::string const& parent, cmFileList& lister) override
  1797. {
  1798. // Glob the set of matching files.
  1799. std::string expr = cmStrCat(parent, this->Pattern);
  1800. cmsys::Glob g;
  1801. if (!g.FindFiles(expr)) {
  1802. return false;
  1803. }
  1804. std::vector<std::string> const& files = g.GetFiles();
  1805. // Look for directories among the matches.
  1806. for (std::string const& f : files) {
  1807. if (cmSystemTools::FileIsDirectory(f)) {
  1808. if (this->Consider(f, lister)) {
  1809. return true;
  1810. }
  1811. }
  1812. }
  1813. return false;
  1814. }
  1815. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1816. {
  1817. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  1818. }
  1819. };
  1820. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  1821. {
  1822. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1823. if (this->DebugMode) {
  1824. fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
  1825. }
  1826. // Skip this if the prefix does not exist.
  1827. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  1828. return false;
  1829. }
  1830. // PREFIX/ (useful on windows or in build trees)
  1831. if (this->SearchDirectory(prefix_in)) {
  1832. return true;
  1833. }
  1834. // Strip the trailing slash because the path generator is about to
  1835. // add one.
  1836. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1837. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  1838. {
  1839. cmFindPackageFileList lister(this);
  1840. lister / cmFileListGeneratorFixed(prefix) /
  1841. cmFileListGeneratorCaseInsensitive("cmake");
  1842. if (lister.Search()) {
  1843. return true;
  1844. }
  1845. }
  1846. // PREFIX/(Foo|foo|FOO).*/
  1847. {
  1848. cmFindPackageFileList lister(this);
  1849. lister / cmFileListGeneratorFixed(prefix) /
  1850. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1851. this->SortDirection);
  1852. if (lister.Search()) {
  1853. return true;
  1854. }
  1855. }
  1856. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  1857. {
  1858. cmFindPackageFileList lister(this);
  1859. lister / cmFileListGeneratorFixed(prefix) /
  1860. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1861. this->SortDirection) /
  1862. cmFileListGeneratorCaseInsensitive("cmake");
  1863. if (lister.Search()) {
  1864. return true;
  1865. }
  1866. }
  1867. // Construct list of common install locations (lib and share).
  1868. std::vector<std::string> common;
  1869. if (!this->LibraryArchitecture.empty()) {
  1870. common.push_back("lib/" + this->LibraryArchitecture);
  1871. }
  1872. if (this->UseLib32Paths) {
  1873. common.emplace_back("lib32");
  1874. }
  1875. if (this->UseLib64Paths) {
  1876. common.emplace_back("lib64");
  1877. }
  1878. if (this->UseLibx32Paths) {
  1879. common.emplace_back("libx32");
  1880. }
  1881. common.emplace_back("lib");
  1882. common.emplace_back("share");
  1883. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1884. {
  1885. cmFindPackageFileList lister(this);
  1886. lister / cmFileListGeneratorFixed(prefix) /
  1887. cmFileListGeneratorEnumerate(common) /
  1888. cmFileListGeneratorFixed("cmake") /
  1889. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1890. this->SortDirection);
  1891. if (lister.Search()) {
  1892. return true;
  1893. }
  1894. }
  1895. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1896. {
  1897. cmFindPackageFileList lister(this);
  1898. lister / cmFileListGeneratorFixed(prefix) /
  1899. cmFileListGeneratorEnumerate(common) /
  1900. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1901. this->SortDirection);
  1902. if (lister.Search()) {
  1903. return true;
  1904. }
  1905. }
  1906. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1907. {
  1908. cmFindPackageFileList lister(this);
  1909. lister / cmFileListGeneratorFixed(prefix) /
  1910. cmFileListGeneratorEnumerate(common) /
  1911. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1912. this->SortDirection) /
  1913. cmFileListGeneratorCaseInsensitive("cmake");
  1914. if (lister.Search()) {
  1915. return true;
  1916. }
  1917. }
  1918. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1919. {
  1920. cmFindPackageFileList lister(this);
  1921. lister / cmFileListGeneratorFixed(prefix) /
  1922. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1923. this->SortDirection) /
  1924. cmFileListGeneratorEnumerate(common) /
  1925. cmFileListGeneratorFixed("cmake") /
  1926. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1927. this->SortDirection);
  1928. if (lister.Search()) {
  1929. return true;
  1930. }
  1931. }
  1932. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1933. {
  1934. cmFindPackageFileList lister(this);
  1935. lister / cmFileListGeneratorFixed(prefix) /
  1936. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1937. this->SortDirection) /
  1938. cmFileListGeneratorEnumerate(common) /
  1939. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1940. this->SortDirection);
  1941. if (lister.Search()) {
  1942. return true;
  1943. }
  1944. }
  1945. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1946. {
  1947. cmFindPackageFileList lister(this);
  1948. lister / cmFileListGeneratorFixed(prefix) /
  1949. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1950. this->SortDirection) /
  1951. cmFileListGeneratorEnumerate(common) /
  1952. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1953. this->SortDirection) /
  1954. cmFileListGeneratorCaseInsensitive("cmake");
  1955. if (lister.Search()) {
  1956. return true;
  1957. }
  1958. }
  1959. return false;
  1960. }
  1961. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  1962. {
  1963. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1964. if (this->DebugMode) {
  1965. fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
  1966. }
  1967. // Strip the trailing slash because the path generator is about to
  1968. // add one.
  1969. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1970. // <prefix>/Foo.framework/Resources/
  1971. {
  1972. cmFindPackageFileList lister(this);
  1973. lister / cmFileListGeneratorFixed(prefix) /
  1974. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1975. cmFileListGeneratorFixed("Resources");
  1976. if (lister.Search()) {
  1977. return true;
  1978. }
  1979. }
  1980. // <prefix>/Foo.framework/Resources/CMake/
  1981. {
  1982. cmFindPackageFileList lister(this);
  1983. lister / cmFileListGeneratorFixed(prefix) /
  1984. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1985. cmFileListGeneratorFixed("Resources") /
  1986. cmFileListGeneratorCaseInsensitive("cmake");
  1987. if (lister.Search()) {
  1988. return true;
  1989. }
  1990. }
  1991. // <prefix>/Foo.framework/Versions/*/Resources/
  1992. {
  1993. cmFindPackageFileList lister(this);
  1994. lister / cmFileListGeneratorFixed(prefix) /
  1995. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1996. cmFileListGeneratorFixed("Versions") /
  1997. cmFileListGeneratorGlob("*/Resources");
  1998. if (lister.Search()) {
  1999. return true;
  2000. }
  2001. }
  2002. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2003. {
  2004. cmFindPackageFileList lister(this);
  2005. lister / cmFileListGeneratorFixed(prefix) /
  2006. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2007. cmFileListGeneratorFixed("Versions") /
  2008. cmFileListGeneratorGlob("*/Resources") /
  2009. cmFileListGeneratorCaseInsensitive("cmake");
  2010. if (lister.Search()) {
  2011. return true;
  2012. }
  2013. }
  2014. return false;
  2015. }
  2016. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2017. {
  2018. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2019. if (this->DebugMode) {
  2020. fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
  2021. }
  2022. // Strip the trailing slash because the path generator is about to
  2023. // add one.
  2024. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2025. // <prefix>/Foo.app/Contents/Resources
  2026. {
  2027. cmFindPackageFileList lister(this);
  2028. lister / cmFileListGeneratorFixed(prefix) /
  2029. cmFileListGeneratorMacProject(this->Names, ".app") /
  2030. cmFileListGeneratorFixed("Contents/Resources");
  2031. if (lister.Search()) {
  2032. return true;
  2033. }
  2034. }
  2035. // <prefix>/Foo.app/Contents/Resources/CMake
  2036. {
  2037. cmFindPackageFileList lister(this);
  2038. lister / cmFileListGeneratorFixed(prefix) /
  2039. cmFileListGeneratorMacProject(this->Names, ".app") /
  2040. cmFileListGeneratorFixed("Contents/Resources") /
  2041. cmFileListGeneratorCaseInsensitive("cmake");
  2042. if (lister.Search()) {
  2043. return true;
  2044. }
  2045. }
  2046. return false;
  2047. }
  2048. // TODO: Debug cmsys::Glob double slash problem.
  2049. bool cmFindPackage(std::vector<std::string> const& args,
  2050. cmExecutionStatus& status)
  2051. {
  2052. return cmFindPackageCommand(status).InitialPass(args);
  2053. }