cmPathResolver.cxx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 "cmPathResolver.h"
  4. #include <algorithm>
  5. #include <cerrno>
  6. #include <cstddef>
  7. #include <string>
  8. #include <utility>
  9. #include <cm/optional>
  10. #include <cm/string_view>
  11. #include <cmext/string_view>
  12. #ifdef _WIN32
  13. # include <cctype>
  14. # include <windows.h>
  15. #endif
  16. #define MAX_SYMBOLIC_LINKS 32
  17. namespace cm {
  18. namespace PathResolver {
  19. namespace {
  20. namespace Options {
  21. enum class ActualCase
  22. {
  23. No,
  24. Yes,
  25. };
  26. enum class Symlinks
  27. {
  28. None,
  29. Lazy,
  30. Eager,
  31. };
  32. enum class Existence
  33. {
  34. Agnostic,
  35. Required,
  36. };
  37. }
  38. enum class Root
  39. {
  40. None,
  41. POSIX,
  42. #ifdef _WIN32
  43. Drive,
  44. Network,
  45. #endif
  46. };
  47. struct Control
  48. {
  49. enum class Tag
  50. {
  51. Continue,
  52. Restart,
  53. Error,
  54. };
  55. Tag tag;
  56. union
  57. {
  58. std::string::size_type slash; // data for Continue
  59. cmsys::Status error; // data for Error
  60. };
  61. static Control Continue(std::string::size_type s)
  62. {
  63. Control c{ Tag::Continue };
  64. c.slash = s;
  65. return c;
  66. }
  67. static Control Restart() { return Control{ Tag::Restart }; }
  68. static Control Error(cmsys::Status e)
  69. {
  70. Control c{ Tag::Error };
  71. c.error = e;
  72. return c;
  73. }
  74. private:
  75. Control(Tag t)
  76. : tag(t)
  77. {
  78. }
  79. };
  80. Root ClassifyRoot(cm::string_view p)
  81. {
  82. #ifdef _WIN32
  83. if (p.size() >= 2 && std::isalpha(p[0]) && p[1] == ':') {
  84. return Root::Drive;
  85. }
  86. if (p.size() >= 3 && p[0] == '/' && p[1] == '/' && p[2] != '/') {
  87. return Root::Network;
  88. }
  89. #endif
  90. if (!p.empty() && p[0] == '/') {
  91. return Root::POSIX;
  92. }
  93. return Root::None;
  94. }
  95. class ImplBase
  96. {
  97. protected:
  98. ImplBase(System& os)
  99. : OS(os)
  100. {
  101. }
  102. System& OS;
  103. std::string P;
  104. std::size_t SymlinkDepth = 0;
  105. #ifdef _WIN32
  106. std::string GetWorkingDirectoryOnDrive(char letter);
  107. Control ResolveRootRelative();
  108. #endif
  109. cm::optional<std::string> ReadSymlink(std::string const& path,
  110. cmsys::Status& status);
  111. Control ResolveSymlink(Root root, std::string::size_type slash,
  112. std::string::size_type next_slash,
  113. std::string symlink_target);
  114. };
  115. template <class Policy>
  116. class Impl : public ImplBase
  117. {
  118. Control ResolveRelativePath();
  119. Control ResolveRoot(Root root);
  120. Control ResolveComponent(Root root, std::string::size_type root_slash,
  121. std::string::size_type slash);
  122. Control ResolvePath();
  123. public:
  124. Impl(System& os)
  125. : ImplBase(os)
  126. {
  127. }
  128. cmsys::Status Resolve(std::string in, std::string& out);
  129. };
  130. template <class Policy>
  131. Control Impl<Policy>::ResolveRelativePath()
  132. {
  133. // This is a relative path. Convert it to absolute and restart.
  134. std::string p = this->OS.GetWorkingDirectory();
  135. std::replace(p.begin(), p.end(), '\\', '/');
  136. if (ClassifyRoot(p) == Root::None) {
  137. p.insert(0, 1, '/');
  138. }
  139. if (p.back() != '/') {
  140. p.push_back('/');
  141. }
  142. P.insert(0, p);
  143. return Control::Restart();
  144. }
  145. #ifdef _WIN32
  146. std::string ImplBase::GetWorkingDirectoryOnDrive(char letter)
  147. {
  148. // Use the drive's working directory, if any.
  149. std::string d = this->OS.GetWorkingDirectoryOnDrive(letter);
  150. std::replace(d.begin(), d.end(), '\\', '/');
  151. if (d.size() >= 3 && std::toupper(d[0]) == std::toupper(letter) &&
  152. d[1] == ':' && d[2] == '/') {
  153. d[0] = letter;
  154. d.push_back('/');
  155. return d;
  156. }
  157. // Use the current working directory if the drive matches.
  158. d = this->OS.GetWorkingDirectory();
  159. if (d.size() >= 3 && std::toupper(d[0]) == std::toupper(letter) &&
  160. d[1] == ':' && d[2] == '/') {
  161. d[0] = letter;
  162. d.push_back('/');
  163. return d;
  164. }
  165. // Fall back to the root directory on the drive.
  166. d = "_:/";
  167. d[0] = letter;
  168. return d;
  169. }
  170. Control ImplBase::ResolveRootRelative()
  171. {
  172. // This is a root-relative path. Resolve the root drive and restart.
  173. P.replace(0, 2, this->GetWorkingDirectoryOnDrive(P[0]));
  174. return Control::Restart();
  175. }
  176. #endif
  177. cm::optional<std::string> ImplBase::ReadSymlink(std::string const& path,
  178. cmsys::Status& status)
  179. {
  180. cm::optional<std::string> result;
  181. std::string target;
  182. status = this->OS.ReadSymlink(path, target);
  183. if (status && ++this->SymlinkDepth >= MAX_SYMBOLIC_LINKS) {
  184. status = cmsys::Status::POSIX(ELOOP);
  185. }
  186. if (status) {
  187. if (!target.empty()) {
  188. result = std::move(target);
  189. }
  190. } else if (status.GetPOSIX() == EINVAL
  191. #ifdef _WIN32
  192. || status.GetWindows() == ERROR_NOT_A_REPARSE_POINT
  193. #endif
  194. ) {
  195. // The path was not a symlink.
  196. status = cmsys::Status::Success();
  197. }
  198. return result;
  199. }
  200. Control ImplBase::ResolveSymlink(Root root, std::string::size_type slash,
  201. std::string::size_type next_slash,
  202. std::string symlink_target)
  203. {
  204. std::replace(symlink_target.begin(), symlink_target.end(), '\\', '/');
  205. Root const symlink_target_root = ClassifyRoot(symlink_target);
  206. if (symlink_target_root == Root::None) {
  207. // This is a symlink to a relative path.
  208. // Resolve the symlink, while preserving the leading and
  209. // trailing (if any) slash:
  210. // "*/link/" => "*/dest/"
  211. // ^slash ^slash
  212. P.replace(slash + 1, next_slash - slash - 1, symlink_target);
  213. return Control::Continue(slash);
  214. }
  215. #ifdef _WIN32
  216. if (root == Root::Drive && symlink_target_root == Root::POSIX) {
  217. // This is a symlink to a POSIX absolute path,
  218. // but the current path is on a drive letter. Resolve the
  219. // symlink while preserving the drive letter, and start over:
  220. // "C:/*/link/" => "C:/dest/"
  221. // ^slash (restart)
  222. P.replace(2, next_slash - 2, symlink_target);
  223. return Control::Restart();
  224. }
  225. #else
  226. static_cast<void>(root);
  227. #endif
  228. // This is a symlink to an absolute path.
  229. // Resolve it and start over:
  230. // "*/link/" => "/dest/"
  231. // ^slash (restart)
  232. P.replace(0, next_slash, symlink_target);
  233. return Control::Restart();
  234. }
  235. template <class Policy>
  236. Control Impl<Policy>::ResolveRoot(Root root)
  237. {
  238. if (root == Root::None) {
  239. return this->ResolveRelativePath();
  240. }
  241. // POSIX absolute paths always start with a '/'.
  242. std::string::size_type root_slash = 0;
  243. #ifdef _WIN32
  244. if (root == Root::Drive) {
  245. if (P.size() == 2 || P[2] != '/') {
  246. return this->ResolveRootRelative();
  247. }
  248. if (Policy::ActualCase == Options::ActualCase::Yes) {
  249. // Normalize the drive letter to upper-case.
  250. P[0] = static_cast<char>(std::toupper(P[0]));
  251. }
  252. // The root is a drive letter. The root '/' immediately follows.
  253. root_slash = 2;
  254. } else if (root == Root::Network) {
  255. // The root is a network name. Find the root '/' after it.
  256. root_slash = P.find('/', 2);
  257. if (root_slash == std::string::npos) {
  258. root_slash = P.size();
  259. P.push_back('/');
  260. }
  261. }
  262. #endif
  263. if (Policy::Existence == Options::Existence::Required
  264. #ifdef _WIN32
  265. && root != Root::Network
  266. #endif
  267. ) {
  268. std::string path = P.substr(0, root_slash + 1);
  269. if (!this->OS.PathExists(path)) {
  270. P = std::move(path);
  271. return Control::Error(cmsys::Status::POSIX(ENOENT));
  272. }
  273. }
  274. return Control::Continue(root_slash);
  275. }
  276. template <class Policy>
  277. Control Impl<Policy>::ResolveComponent(Root root,
  278. std::string::size_type root_slash,
  279. std::string::size_type slash)
  280. {
  281. // Look for the '/' or end-of-input that ends this component.
  282. // The sample paths in comments below show the trailing slash
  283. // even if it is actually beyond the end of the path.
  284. std::string::size_type next_slash = P.find('/', slash + 1);
  285. if (next_slash == std::string::npos) {
  286. next_slash = P.size();
  287. }
  288. cm::string_view c =
  289. cm::string_view(P).substr(slash + 1, next_slash - (slash + 1));
  290. if (slash == root_slash) {
  291. if (c.empty() || c == "."_s || c == ".."_s) {
  292. // This is an empty, '.', or '..' component at the root.
  293. // Drop the component and its trailing slash, if any,
  294. // while preserving the root slash:
  295. // "//" => "/"
  296. // "/./" => "/"
  297. // "/../" => "/"
  298. // ^slash ^slash
  299. P.erase(slash + 1, next_slash - slash);
  300. return Control::Continue(slash);
  301. }
  302. } else {
  303. if (c.empty() || c == "."_s) {
  304. // This is an empty or '.' component not at the root.
  305. // Drop the component and its leading slash:
  306. // "*//" => "*/"
  307. // "*/./" => "*/"
  308. // ^slash ^slash
  309. P.erase(slash, next_slash - slash);
  310. return Control::Continue(slash);
  311. }
  312. if (c == ".."_s) {
  313. // This is a '..' component not at the root.
  314. // Rewind to the previous component:
  315. // "*/prev/../" => "*/prev/../"
  316. // ^slash ^slash
  317. next_slash = slash;
  318. slash = P.rfind('/', slash - 1);
  319. if (Policy::Symlinks == Options::Symlinks::Lazy) {
  320. cmsys::Status status;
  321. std::string path = P.substr(0, next_slash);
  322. if (cm::optional<std::string> maybe_symlink_target =
  323. this->ReadSymlink(path, status)) {
  324. return this->ResolveSymlink(root, slash, next_slash,
  325. std::move(*maybe_symlink_target));
  326. }
  327. if (!status && Policy::Existence == Options::Existence::Required) {
  328. P = std::move(path);
  329. return Control::Error(status);
  330. }
  331. }
  332. // This is not a symlink.
  333. // Drop the component, the following '..', and its trailing slash,
  334. // if any, while preserving the (possibly root) leading slash:
  335. // "*/dir/../" => "*/"
  336. // ^slash ^slash
  337. P.erase(slash + 1, next_slash + 3 - slash);
  338. return Control::Continue(slash);
  339. }
  340. }
  341. // This is a named component.
  342. if (Policy::Symlinks == Options::Symlinks::Eager) {
  343. cmsys::Status status;
  344. std::string path = P.substr(0, next_slash);
  345. if (cm::optional<std::string> maybe_symlink_target =
  346. this->ReadSymlink(path, status)) {
  347. return this->ResolveSymlink(root, slash, next_slash,
  348. std::move(*maybe_symlink_target));
  349. }
  350. if (!status && Policy::Existence == Options::Existence::Required) {
  351. P = std::move(path);
  352. return Control::Error(status);
  353. }
  354. }
  355. #if defined(_WIN32) || defined(__APPLE__)
  356. bool exists = false;
  357. if (Policy::ActualCase == Options::ActualCase::Yes) {
  358. std::string name;
  359. std::string path = P.substr(0, next_slash);
  360. if (cmsys::Status status = this->OS.ReadName(path, name)) {
  361. exists = true;
  362. if (!name.empty()) {
  363. // Rename this component:
  364. // "*/name/" => "*/Name/"
  365. // ^slash ^slash
  366. P.replace(slash + 1, next_slash - slash - 1, name);
  367. next_slash = slash + 1 + name.length();
  368. }
  369. } else if (Policy::Existence == Options::Existence::Required) {
  370. P = std::move(path);
  371. return Control::Error(status);
  372. }
  373. }
  374. #endif
  375. if (Policy::Existence == Options::Existence::Required
  376. #if defined(_WIN32) || defined(__APPLE__)
  377. && !exists
  378. #endif
  379. ) {
  380. std::string path = P.substr(0, next_slash);
  381. if (!this->OS.PathExists(path)) {
  382. P = std::move(path);
  383. return Control::Error(cmsys::Status::POSIX(ENOENT));
  384. }
  385. }
  386. // Keep this component:
  387. // "*/name/" => "*/name/"
  388. // ^slash ^slash
  389. return Control::Continue(next_slash);
  390. }
  391. template <class Policy>
  392. Control Impl<Policy>::ResolvePath()
  393. {
  394. Root const root = ClassifyRoot(P);
  395. // Resolve the root component. It always ends in a slash.
  396. Control control = this->ResolveRoot(root);
  397. if (control.tag != Control::Tag::Continue) {
  398. return control;
  399. }
  400. std::string::size_type const root_slash = control.slash;
  401. // Resolve later components. Every iteration that finishes
  402. // the loop body makes progress either by removing a component
  403. // or advancing the slash past it.
  404. for (std::string::size_type slash = root_slash;
  405. P.size() > root_slash + 1 && slash < P.size();) {
  406. control = this->ResolveComponent(root, root_slash, slash);
  407. if (control.tag != Control::Tag::Continue) {
  408. return control;
  409. }
  410. slash = control.slash;
  411. }
  412. return Control::Continue(P.size());
  413. }
  414. template <class Policy>
  415. cmsys::Status Impl<Policy>::Resolve(std::string in, std::string& out)
  416. {
  417. P = std::move(in);
  418. std::replace(P.begin(), P.end(), '\\', '/');
  419. for (;;) {
  420. Control control = this->ResolvePath();
  421. switch (control.tag) {
  422. case Control::Tag::Continue:
  423. out = std::move(P);
  424. return cmsys::Status::Success();
  425. case Control::Tag::Restart:
  426. continue;
  427. case Control::Tag::Error:
  428. out = std::move(P);
  429. return control.error;
  430. };
  431. }
  432. }
  433. }
  434. namespace Policies {
  435. struct NaivePath
  436. {
  437. #if defined(_WIN32) || defined(__APPLE__)
  438. static constexpr Options::ActualCase ActualCase = Options::ActualCase::No;
  439. #endif
  440. static constexpr Options::Symlinks Symlinks = Options::Symlinks::None;
  441. static constexpr Options::Existence Existence = Options::Existence::Agnostic;
  442. };
  443. struct RealPath
  444. {
  445. #if defined(_WIN32) || defined(__APPLE__)
  446. static constexpr Options::ActualCase ActualCase = Options::ActualCase::Yes;
  447. #endif
  448. static constexpr Options::Symlinks Symlinks = Options::Symlinks::Eager;
  449. static constexpr Options::Existence Existence = Options::Existence::Required;
  450. };
  451. struct LogicalPath
  452. {
  453. #if defined(_WIN32) || defined(__APPLE__)
  454. static constexpr Options::ActualCase ActualCase = Options::ActualCase::Yes;
  455. #endif
  456. static constexpr Options::Symlinks Symlinks = Options::Symlinks::Lazy;
  457. static constexpr Options::Existence Existence = Options::Existence::Agnostic;
  458. };
  459. #if defined(__SUNPRO_CC)
  460. constexpr Options::Symlinks NaivePath::Symlinks;
  461. constexpr Options::Existence NaivePath::Existence;
  462. constexpr Options::Symlinks RealPath::Symlinks;
  463. constexpr Options::Existence RealPath::Existence;
  464. constexpr Options::Symlinks LogicalPath::Symlinks;
  465. constexpr Options::Existence LogicalPath::Existence;
  466. #endif
  467. }
  468. template <class Policy>
  469. Resolver<Policy>::Resolver(System& os)
  470. : OS(os)
  471. {
  472. }
  473. template <class Policy>
  474. cmsys::Status Resolver<Policy>::Resolve(std::string in, std::string& out) const
  475. {
  476. return Impl<Policy>(OS).Resolve(std::move(in), out);
  477. }
  478. System::System() = default;
  479. System::~System() = default;
  480. template class Resolver<Policies::LogicalPath>;
  481. template class Resolver<Policies::RealPath>;
  482. template class Resolver<Policies::NaivePath>;
  483. }
  484. }