1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // FilePath is a container for pathnames stored in a platform's native string
6 // type, providing containers for manipulation in according with the
7 // platform's conventions for pathnames.  It supports the following path
8 // types:
9 //
10 //                   POSIX            Windows
11 //                   ---------------  ----------------------------------
12 // Fundamental type  char[]           wchar_t[]
13 // Encoding          unspecified*     UTF-16
14 // Separator         /                \, tolerant of /
15 // Drive letters     no               case-insensitive A-Z followed by :
16 // Alternate root    // (surprise!)   \\ (2 Separators), for UNC paths
17 //
18 // * The encoding need not be specified on POSIX systems, although some
19 //   POSIX-compliant systems do specify an encoding.  Mac OS X uses UTF-8.
20 //   Chrome OS also uses UTF-8.
21 //   Linux does not specify an encoding, but in practice, the locale's
22 //   character set may be used.
23 //
24 // For more arcane bits of path trivia, see below.
25 //
26 // FilePath objects are intended to be used anywhere paths are.  An
27 // application may pass FilePath objects around internally, masking the
28 // underlying differences between systems, only differing in implementation
29 // where interfacing directly with the system.  For example, a single
30 // OpenFile(const FilePath &) function may be made available, allowing all
31 // callers to operate without regard to the underlying implementation.  On
32 // POSIX-like platforms, OpenFile might wrap fopen, and on Windows, it might
33 // wrap _wfopen_s, perhaps both by calling file_path.value().c_str().  This
34 // allows each platform to pass pathnames around without requiring conversions
35 // between encodings, which has an impact on performance, but more imporantly,
36 // has an impact on correctness on platforms that do not have well-defined
37 // encodings for pathnames.
38 //
39 // Several methods are available to perform common operations on a FilePath
40 // object, such as determining the parent directory (DirName), isolating the
41 // final path component (BaseName), and appending a relative pathname string
42 // to an existing FilePath object (Append).  These methods are highly
43 // recommended over attempting to split and concatenate strings directly.
44 // These methods are based purely on string manipulation and knowledge of
45 // platform-specific pathname conventions, and do not consult the filesystem
46 // at all, making them safe to use without fear of blocking on I/O operations.
47 // These methods do not function as mutators but instead return distinct
48 // instances of FilePath objects, and are therefore safe to use on const
49 // objects.  The objects themselves are safe to share between threads.
50 //
51 // To aid in initialization of FilePath objects from string literals, a
52 // FILE_PATH_LITERAL macro is provided, which accounts for the difference
53 // between char[]-based pathnames on POSIX systems and wchar_t[]-based
54 // pathnames on Windows.
55 //
56 // As a precaution against premature truncation, paths can't contain NULs.
57 //
58 // Because a FilePath object should not be instantiated at the global scope,
59 // instead, use a FilePath::CharType[] and initialize it with
60 // FILE_PATH_LITERAL.  At runtime, a FilePath object can be created from the
61 // character array.  Example:
62 //
63 // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
64 // |
65 // | void Function() {
66 // |   FilePath log_file_path(kLogFileName);
67 // |   [...]
68 // | }
69 //
70 // WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
71 // when the UI language is RTL. This means you always need to pass filepaths
72 // through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
73 // RTL UI.
74 //
75 // This is a very common source of bugs, please try to keep this in mind.
76 //
77 // ARCANE BITS OF PATH TRIVIA
78 //
79 //  - A double leading slash is actually part of the POSIX standard.  Systems
80 //    are allowed to treat // as an alternate root, as Windows does for UNC
81 //    (network share) paths.  Most POSIX systems don't do anything special
82 //    with two leading slashes, but FilePath handles this case properly
83 //    in case it ever comes across such a system.  FilePath needs this support
84 //    for Windows UNC paths, anyway.
85 //    References:
86 //    The Open Group Base Specifications Issue 7, sections 3.267 ("Pathname")
87 //    and 4.12 ("Pathname Resolution"), available at:
88 //    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267
89 //    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
90 //
91 //  - Windows treats c:\\ the same way it treats \\.  This was intended to
92 //    allow older applications that require drive letters to support UNC paths
93 //    like \\server\share\path, by permitting c:\\server\share\path as an
94 //    equivalent.  Since the OS treats these paths specially, FilePath needs
95 //    to do the same.  Since Windows can use either / or \ as the separator,
96 //    FilePath treats c://, c:\\, //, and \\ all equivalently.
97 //    Reference:
98 //    The Old New Thing, "Why is a drive letter permitted in front of UNC
99 //    paths (sometimes)?", available at:
100 //    http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
101 
102 #ifndef PARTITION_ALLOC_PARTITION_ALLOC_BASE_FILES_FILE_PATH_H_
103 #define PARTITION_ALLOC_PARTITION_ALLOC_BASE_FILES_FILE_PATH_H_
104 
105 #include <cstddef>
106 #include <iosfwd>
107 #include <string>
108 
109 #include "build/build_config.h"
110 #include "partition_alloc/partition_alloc_base/component_export.h"
111 
112 // Windows-style drive letter support and pathname separator characters can be
113 // enabled and disabled independently, to aid testing.  These #defines are
114 // here so that the same setting can be used in both the implementation and
115 // in the unit test.
116 #if BUILDFLAG(IS_WIN)
117 #define PA_FILE_PATH_USES_DRIVE_LETTERS
118 #define PA_FILE_PATH_USES_WIN_SEPARATORS
119 #endif  // BUILDFLAG(IS_WIN)
120 
121 // Macros for string literal initialization of FilePath::CharType[].
122 #if BUILDFLAG(IS_WIN)
123 #define PA_FILE_PATH_LITERAL(x) L##x
124 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
125 #define PA_FILE_PATH_LITERAL(x) x
126 #endif  // BUILDFLAG(IS_WIN)
127 
128 namespace partition_alloc::internal::base {
129 
130 // An abstraction to isolate users from the differences between native
131 // pathnames on different platforms.
PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE)132 class PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE) FilePath {
133  public:
134 #if BUILDFLAG(IS_WIN)
135   // On Windows, for Unicode-aware applications, native pathnames are wchar_t
136   // arrays encoded in UTF-16.
137   typedef std::wstring StringType;
138 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
139   // On most platforms, native pathnames are char arrays, and the encoding
140   // may or may not be specified.  On Mac OS X, native pathnames are encoded
141   // in UTF-8.
142   typedef std::string StringType;
143 #endif  // BUILDFLAG(IS_WIN)
144 
145   typedef StringType::value_type CharType;
146 
147   // Null-terminated array of separators used to separate components in paths.
148   // Each character in this array is a valid separator, but kSeparators[0] is
149   // treated as the canonical separator and is used when composing pathnames.
150   static constexpr CharType kSeparators[] =
151 #if defined(PA_FILE_PATH_USES_WIN_SEPARATORS)
152       PA_FILE_PATH_LITERAL("\\/");
153 #else   // PA_FILE_PATH_USES_WIN_SEPARATORS
154       PA_FILE_PATH_LITERAL("/");
155 #endif  // PA_FILE_PATH_USES_WIN_SEPARATORS
156 
157   // std::size(kSeparators), i.e., the number of separators in kSeparators plus
158   // one (the null terminator at the end of kSeparators).
159   static constexpr size_t kSeparatorsLength = std::size(kSeparators);
160 
161   // The special path component meaning "this directory."
162   static constexpr CharType kCurrentDirectory[] = PA_FILE_PATH_LITERAL(".");
163 
164   // The special path component meaning "the parent directory."
165   static constexpr CharType kParentDirectory[] = PA_FILE_PATH_LITERAL("..");
166 
167   // The character used to identify a file extension.
168   static constexpr CharType kExtensionSeparator = PA_FILE_PATH_LITERAL('.');
169 
170   FilePath();
171   FilePath(const FilePath& that);
172   explicit FilePath(const StringType& that);
173   ~FilePath();
174   FilePath& operator=(const FilePath& that);
175 
176   // Constructs FilePath with the contents of |that|, which is left in valid but
177   // unspecified state.
178   FilePath(FilePath&& that) noexcept;
179   // Replaces the contents with those of |that|, which is left in valid but
180   // unspecified state.
181   FilePath& operator=(FilePath&& that) noexcept;
182 
183   // Required for some STL containers and operations
184   bool operator<(const FilePath& that) const { return path_ < that.path_; }
185 
186   const StringType& value() const { return path_; }
187 
188   [[nodiscard]] bool empty() const { return path_.empty(); }
189 
190   void clear() { path_.clear(); }
191 
192   // Returns true if |character| is in kSeparators.
193   static bool IsSeparator(CharType character);
194 
195   // Returns a FilePath by appending a separator and the supplied path
196   // component to this object's path.  Append takes care to avoid adding
197   // excessive separators if this object's path already ends with a separator.
198   // If this object's path is kCurrentDirectory, a new FilePath corresponding
199   // only to |component| is returned.  |component| must be a relative path;
200   // it is an error to pass an absolute path.
201   [[nodiscard]] FilePath Append(const FilePath& component) const;
202   [[nodiscard]] FilePath Append(const StringType& component) const;
203 
204  private:
205   // Remove trailing separators from this object.  If the path is absolute, it
206   // will never be stripped any more than to refer to the absolute root
207   // directory, so "////" will become "/", not "".  A leading pair of
208   // separators is never stripped, to support alternate roots.  This is used to
209   // support UNC paths on Windows.
210   void StripTrailingSeparatorsInternal();
211 
212   StringType path_;
213 };
214 
215 }  // namespace partition_alloc::internal::base
216 
217 namespace std {
218 
219 template <>
220 struct hash<::partition_alloc::internal::base::FilePath> {
221   typedef ::partition_alloc::internal::base::FilePath argument_type;
222   typedef std::size_t result_type;
223   result_type operator()(argument_type const& f) const {
224     return hash<::partition_alloc::internal::base::FilePath::StringType>()(
225         f.value());
226   }
227 };
228 
229 }  // namespace std
230 
231 #endif  // PARTITION_ALLOC_PARTITION_ALLOC_BASE_FILES_FILE_PATH_H_
232