HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
fileSystem.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the Apache License, Version 2.0 (the "Apache License")
5 // with the following modification; you may not use this file except in
6 // compliance with the Apache License and the following modification to it:
7 // Section 6. Trademarks. is deleted and replaced with:
8 //
9 // 6. Trademarks. This License does not grant permission to use the trade
10 // names, trademarks, service marks, or product names of the Licensor
11 // and its affiliates, except as required to comply with Section 4(c) of
12 // the License and to reproduce the content of the NOTICE file.
13 //
14 // You may obtain a copy of the Apache License at
15 //
16 // http://www.apache.org/licenses/LICENSE-2.0
17 //
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the Apache License with the above modification is
20 // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21 // KIND, either express or implied. See the Apache License for the specific
22 // language governing permissions and limitations under the Apache License.
23 //
24 #ifndef PXR_BASE_ARCH_FILE_SYSTEM_H
25 #define PXR_BASE_ARCH_FILE_SYSTEM_H
26 
27 /// \file arch/fileSystem.h
28 /// \ingroup group_arch_SystemFunctions
29 /// Architecture dependent file system access
30 
31 #include "pxr/pxr.h"
32 #include "pxr/base/arch/api.h"
33 #include "pxr/base/arch/defines.h"
34 #include "pxr/base/arch/inttypes.h"
35 #include <memory>
36 #include <cstdio>
37 #include <string>
38 #include <set>
39 
40 #include <fcntl.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 
44 #if defined(ARCH_OS_LINUX)
45 #include <unistd.h>
46 #include <sys/statfs.h>
47 #include <glob.h>
48 #elif defined(ARCH_OS_DARWIN)
49 #include <unistd.h>
50 #include <sys/mount.h>
51 #include <glob.h>
52 #elif defined(ARCH_OS_WINDOWS)
53 #include <io.h>
54 #include <windows.h>
55 #include <stringapiset.h>
56 #endif
57 
59 
60 /// \addtogroup group_arch_SystemFunctions
61 ///@{
62 #if !defined(ARCH_OS_WINDOWS)
63  #ifdef _POSIX_VERSION
64  #include <limits.h> /* for PATH_MAX */
65  #else
66  #include <sys/param.h> /* for MAXPATHLEN */
67  #endif
68 #else
69  // XXX -- Should probably have ARCH_ macro for this.
70  #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
71 
72  // See https://msdn.microsoft.com/en-us/library/1w06ktdy.aspx
73  // XXX -- Should probably have Arch enum for these.
74  #define F_OK 0 // Test for existence.
75  #define X_OK 1 // Test for execute permission.
76  #define W_OK 2 // Test for write permission.
77  #define R_OK 4 // Test for read permission.
78 #endif
79 
80 #if defined(ARCH_OS_WINDOWS)
81  #define ARCH_GLOB_NOCHECK 1
82  #define ARCH_GLOB_MARK 2
83  #define ARCH_GLOB_NOSORT 4
84 #else
85  #define ARCH_GLOB_NOCHECK GLOB_NOCHECK
86  #define ARCH_GLOB_MARK GLOB_MARK
87  #define ARCH_GLOB_NOSORT GLOB_NOSORT
88 #endif
89 #define ARCH_GLOB_DEFAULT (ARCH_GLOB_NOCHECK | ARCH_GLOB_MARK)
90 
91 #ifndef ARCH_PATH_MAX
92  #ifdef PATH_MAX
93  #define ARCH_PATH_MAX PATH_MAX
94  #else
95  #ifdef MAXPATHLEN
96  #define ARCH_PATH_MAX MAXPATHLEN
97  #else
98  #ifdef _MAX_PATH
99  #define ARCH_PATH_MAX _MAX_PATH
100  #else
101  #define ARCH_PATH_MAX 1024
102  #endif
103  #endif
104  #endif
105 #endif
106 
107 #if defined(ARCH_OS_WINDOWS)
108  #define ARCH_PATH_SEP "\\"
109  #define ARCH_PATH_LIST_SEP ";"
110  #define ARCH_REL_PATH_IDENT ".\\"
111 #else
112  #define ARCH_PATH_SEP "/"
113  #define ARCH_PATH_LIST_SEP ":"
114  #define ARCH_REL_PATH_IDENT "./"
115 #endif
116 
117 #if defined(ARCH_OS_WINDOWS)
118 typedef struct __stat64 ArchStatType;
119 #else
120 typedef struct stat ArchStatType;
121 #endif
122 
123 /// \file fileSystem.h
124 /// Architecture dependent file system access
125 /// \ingroup group_arch_SystemFunctions
126 ///
127 
128 /// Opens a file.
129 ///
130 /// Opens the file that is specified by filename.
131 /// Returning true if the file was opened successfully; false otherwise.
132 ///
133 ARCH_API FILE*
134 ArchOpenFile(char const* fileName, char const* mode);
135 
136 #if defined(ARCH_OS_WINDOWS)
137 # define ArchChmod(path, mode) _chmod(path, mode)
138 #else
139 # define ArchChmod(path, mode) chmod(path, mode)
140 #endif
141 
142 #if defined(ARCH_OS_WINDOWS)
143 # define ArchCloseFile(fd) _close(fd)
144 #else
145 # define ArchCloseFile(fd) close(fd)
146 #endif
147 
148 #if defined(ARCH_OS_WINDOWS)
149 # define ArchUnlinkFile(path) _unlink(path)
150 #else
151 # define ArchUnlinkFile(path) unlink(path)
152 #endif
153 
154 #if defined(ARCH_OS_WINDOWS)
155  ARCH_API int ArchFileAccess(const char* path, int mode);
156 #else
157 # define ArchFileAccess(path, mode) access(path, mode)
158 #endif
159 
160 #if defined(ARCH_OS_WINDOWS)
161 # define ArchFdOpen(fd, mode) _fdopen(fd, mode)
162 #else
163 # define ArchFdOpen(fd, mode) fdopen(fd, mode)
164 #endif
165 
166 #if defined(ARCH_OS_WINDOWS)
167 # define ArchFileNo(stream) _fileno(stream)
168 #else
169 # define ArchFileNo(stream) fileno(stream)
170 #endif
171 
172 #if defined(ARCH_OS_WINDOWS)
173 # define ArchFileIsaTTY(stream) _isatty(stream)
174 #else
175 # define ArchFileIsaTTY(stream) isatty(stream)
176 #endif
177 
178 #if defined(ARCH_OS_WINDOWS)
179  ARCH_API int ArchRmDir(const char* path);
180 #else
181 # define ArchRmDir(path) rmdir(path)
182 #endif
183 
184 /// Return the length of a file in bytes.
185 ///
186 /// Returns -1 if the file cannot be opened/read.
187 ARCH_API int64_t ArchGetFileLength(const char* fileName);
188 ARCH_API int64_t ArchGetFileLength(FILE *file);
189 
190 /// Return a filename for this file, if one can be obtained. Note that there
191 /// are many reasons why it may be impossible to obtain a filename, even for an
192 /// opened FILE *. Whenever possible avoid using this function and instead
193 /// store the filename for future use.
195 
196 /// Returns true if the data in \c stat struct \p st indicates that the target
197 /// file or directory is writable.
198 ///
199 /// This returns true if the struct pointer is valid, and the stat indicates
200 /// the target is writable by the effective user, effective group, or all
201 /// users.
203 
204 /// Returns the modification time (mtime) in seconds for a file.
205 ///
206 /// This function stores the modification time with as much precision as is
207 /// available in the stat structure for the current platform in \p time and
208 /// returns \c true on success, otherwise just returns \c false.
209 ARCH_API bool ArchGetModificationTime(const char* pathname, double* time);
210 
211 /// Returns the modification time (mtime) in seconds from the stat struct.
212 ///
213 /// This function returns the modification time with as much precision as is
214 /// available in the stat structure for the current platform.
216 
217 /// Normalizes the specified path, eliminating double slashes, etc.
218 ///
219 /// This canonicalizes paths, removing any double slashes, and eliminiating
220 /// '.', and '..' components of the path. This emulates the behavior of
221 /// os.path.normpath in Python.
222 ///
223 /// On Windows, all backslashes are converted to forward slashes and drive
224 /// specifiers (e.g., "C:") are lower-cased. If \p stripDriveSpecifier
225 /// is \c true, these drive specifiers are removed from the path.
227  bool stripDriveSpecifier = false);
228 
229 /// Returns the canonical absolute path of the specified filename.
230 ///
231 /// This makes the specified path absolute, by prepending the current working
232 /// directory. If the path is already absolute, it is returned unmodified.
234 
235 /// Returns the permissions mode (mode_t) for the given pathname.
236 ///
237 /// This function stats the given pathname and returns the permissions flags
238 /// for it and returns true. If the stat fails, returns false.
239 ///
240 ARCH_API bool ArchGetStatMode(const char *pathname, int *mode);
241 
242 /// Return the path to a temporary directory for this platform.
243 ///
244 /// The returned temporary directory will be a location that will normally
245 /// be cleaned out on a reboot. This is /var/tmp on Linux machines (for
246 /// legacy reasons), but /tmp on Darwin machines (/var/tmp on Darwin is
247 /// specified as a location where files are kept between system reboots -
248 /// see "man hier"). The returned string will not have a trailing slash.
249 ///
250 /// This routine is threadsafe and will not perform any memory allocations.
251 ARCH_API const char *ArchGetTmpDir();
252 
253 /// Make a temporary file name, in a system-determined temporary directory.
254 ///
255 /// The result returned has the form TMPDIR/prefix.pid[.n]suffix where TMPDIR
256 /// is a system-determined temporary directory (typically /tmp or /usr/tmp),
257 /// pid is the process id of the process, and the optional .n records the
258 /// number of times this function has been called by a process (and is ommited
259 /// the first time this function is called).
260 ///
261 /// The call is threadsafe.
262 ///
263 /// \warning This call opens a security hole because of the race between
264 /// choosing the name and opening the file. This call should be avoided in
265 /// favor of \c ArchMakeTmpFile().
266 ARCH_API
268  const std::string& suffix = std::string());
269 
270 /// Create a temporary file, in a system-determined temporary directory.
271 ///
272 /// The result returned has the form TMPDIR/prefix.XXXXXX where TMPDIR is a
273 /// system-determined temporary directory (typically /tmp or /usr/tmp) and
274 /// XXXXXX is a unique suffix. Returns the file descriptor of the new file
275 /// and, if pathname isn't NULL, returns the full path to the file in
276 /// pathname. Returns -1 on failure and errno is set.
277 ///
278 /// The call is threadsafe.
279 ARCH_API
280 int ArchMakeTmpFile(const std::string& prefix, std::string* pathname = 0);
281 
282 /// Create a temporary file, in a given temporary directory.
283 ///
284 /// The result returned has the form TMPDIR/prefix.XXXXXX where TMPDIR is the
285 /// given temporary directory and XXXXXX is a unique suffix. Returns the file
286 /// descriptor of the new file and, if pathname isn't NULL, returns the full
287 /// path to the file in pathname. Returns -1 on failure and errno is set.
288 ///
289 /// The call is threadsafe.
290 ARCH_API
291 int ArchMakeTmpFile(const std::string& tmpdir,
292  const std::string& prefix, std::string* pathname = 0);
293 
294 /// Create a temporary sub-direcrory, in a given temporary directory.
295 ///
296 /// The result returned has the form TMPDIR/prefix.XXXXXX/ where TMPDIR is the
297 /// given temporary directory and XXXXXX is a unique suffix. Returns the the
298 /// full path to the subdir in pathname. Returns empty string on failure and
299 /// errno is set.
300 ///
301 /// The call is threadsafe.
302 ARCH_API
304  const std::string& prefix);
305 
306 // Helper 'deleter' for use with std::unique_ptr for file mappings.
308  Arch_Unmapper() : _length(~0) {}
309  explicit Arch_Unmapper(size_t length) : _length(length) {}
310  ARCH_API void operator()(char *mapStart) const;
311  ARCH_API void operator()(char const *mapStart) const;
312  size_t GetLength() const { return _length; }
313 private:
314  size_t _length;
315 };
316 
317 /// ArchConstFileMapping and ArchMutableFileMapping are std::unique_ptr<char
318 /// const *, ...> and std::unique_ptr<char *, ...> respectively. The functions
319 /// ArchMapFileReadOnly() and ArchMapFileReadWrite() return them and provide
320 /// access to memory-mapped file contents.
321 using ArchConstFileMapping = std::unique_ptr<char const, Arch_Unmapper>;
322 using ArchMutableFileMapping = std::unique_ptr<char, Arch_Unmapper>;
323 
324 /// Return the length of an ArchConstFileMapping.
325 inline size_t
327  return m.get_deleter().GetLength();
328 }
329 
330 /// Return the length of an ArchMutableFileMapping.
331 inline size_t
333  return m.get_deleter().GetLength();
334 }
335 
336 /// Privately map the passed \p file into memory and return a unique_ptr to the
337 /// read-only mapped contents. The contents may not be modified. If mapping
338 /// fails, return a null unique_ptr and if errMsg is not null fill it with
339 /// information about the failure.
340 ARCH_API
342 ArchMapFileReadOnly(FILE *file, std::string *errMsg=nullptr);
343 
344 /// \overload
345 ARCH_API
347 ArchMapFileReadOnly(std::string const& path, std::string *errMsg=nullptr);
348 
349 /// Privately map the passed \p file into memory and return a unique_ptr to the
350 /// copy-on-write mapped contents. If modified, the affected pages are
351 /// dissociated from the underlying file and become backed by the system's swap
352 /// or page-file storage. Edits are not carried through to the underlying file.
353 /// If mapping fails, return a null unique_ptr and if errMsg is not null fill it
354 /// with information about the failure.
355 ARCH_API
357 ArchMapFileReadWrite(FILE *file, std::string *errMsg=nullptr);
358 
359 /// \overload
360 ARCH_API
362 ArchMapFileReadWrite(std::string const& path, std::string *errMsg=nullptr);
363 
365  ArchMemAdviceNormal, // Treat range with default behavior.
366  ArchMemAdviceWillNeed, // OS may prefetch this range.
367  ArchMemAdviceDontNeed, // OS may free resources related to this range.
368  ArchMemAdviceRandomAccess, // Prefetching may not be beneficial.
369 };
370 
371 /// Advise the OS regarding how the application intends to access a range of
372 /// memory. See ArchMemAdvice. This is primarily useful for mapped file
373 /// regions. This call does not change program semantics. It is only an
374 /// optimization hint to the OS, and may be a no-op on some systems.
375 ARCH_API
376 void ArchMemAdvise(void const *addr, size_t len, ArchMemAdvice adv);
377 
378 /// Report whether or not the mapped virtual memory pages starting at \p addr
379 /// for \p len bytes are resident in RAM. Pages that are resident will not,
380 /// when accessed, cause a page fault while those that are not will. Return
381 /// true on success and false in case of an error. The \p addr argument must be
382 /// a multiple of ArchGetPageSize(). The \p len argument need not be a multiple
383 /// of the page size; it will be rounded up to the next page boundary. Fill
384 /// \p pageMap with 0s for pages not resident in memory and 1s for pages that
385 /// are. The \p pageMap argument must therefore point to at least (\p len +
386 /// ArchGetPageSize()-1)/ArchGetPageSize() bytes.
387 ///
388 /// Note that currently this function is only implemented on Linux and Darwin.
389 /// On Windows it currently always returns false.
390 ARCH_API
391 bool
393  void const *addr, size_t len, unsigned char *pageMap);
394 
395 /// Read up to \p count bytes from \p offset in \p file into \p buffer. The
396 /// file position indicator for \p file is not changed. Return the number of
397 /// bytes read, or zero if at end of file. Return -1 in case of an error, with
398 /// errno set appropriately.
399 ARCH_API
400 int64_t ArchPRead(FILE *file, void *buffer, size_t count, int64_t offset);
401 
402 /// Write up to \p count bytes from \p buffer to \p file at \p offset. The file
403 /// position indicator for \p file is not changed. Return the number of bytes
404 /// written, possibly zero if none written. Return -1 in case of an error, with
405 /// errno set appropriately.
406 ARCH_API
407 int64_t ArchPWrite(FILE *file, void const *bytes, size_t count, int64_t offset);
408 
409 /// Returns the value of the symbolic link at \p path. Returns the empty
410 /// string on error or if \p path does not refer to a symbolic link.
411 ARCH_API
412 std::string ArchReadLink(const char* path);
413 
415  ArchFileAdviceNormal, // Treat range with default behavior.
416  ArchFileAdviceWillNeed, // OS may prefetch this range.
417  ArchFileAdviceDontNeed, // OS may free resources related to this range.
418  ArchFileAdviceRandomAccess, // Prefetching may not be beneficial.
419 };
420 
421 /// Advise the OS regarding how the application intends to access a range of
422 /// bytes in a file. See ArchFileAdvice. This call does not change program
423 /// semantics. It is only an optimization hint to the OS, and may be a no-op on
424 /// some systems.
425 ARCH_API
426 void ArchFileAdvise(FILE *file, int64_t offset, size_t count,
427  ArchFileAdvice adv);
428 
429 #if defined(ARCH_OS_WINDOWS)
430 
431 /// Converts UTF-16 windows string to regular std::string - Windows-only
432 inline std::string ArchWindowsUtf16ToUtf8(const std::wstring &wstr)
433 {
434  if (wstr.empty()) return std::string();
435  // first call is only to get required size for string
436  int size = WideCharToMultiByte(
437  CP_UTF8, 0, wstr.data(), (int)wstr.size(), NULL, 0, NULL, NULL);
438  if (size == 0) return std::string();
439  std::string str(size, 0);
440  if (WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(),
441  &str[0], size, NULL, NULL) == 0) {
442  return std::string();
443  }
444  return str;
445 }
446 
447 /// Converts regular std::string to UTF-16 windows string - Windows-only
448 inline std::wstring ArchWindowsUtf8ToUtf16(const std::string &str)
449 {
450  if (str.empty()) return std::wstring();
451  // first call is only to get required size for wstring
452  int size = MultiByteToWideChar(
453  CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0);
454  if (size == 0) return std::wstring();
455  std::wstring wstr(size, 0);
456  if(MultiByteToWideChar(
457  CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0], size) == 0) {
458  return std::wstring();
459  }
460  return wstr;
461 }
462 
463 #endif
464 
465 ///@}
466 
468 
469 #endif // PXR_BASE_ARCH_FILE_SYSTEM_H
ArchFileAdvice
Definition: fileSystem.h:414
typedef int(APIENTRYP RE_PFNGLXSWAPINTERVALSGIPROC)(int)
ARCH_API FILE * ArchOpenFile(char const *fileName, char const *mode)
ARCH_API void ArchMemAdvise(void const *addr, size_t len, ArchMemAdvice adv)
GT_API const UT_StringHolder time
GLsizei const GLchar *const * string
Definition: glcorearb.h:814
GLsizei const GLchar *const * path
Definition: glcorearb.h:3341
ARCH_API std::string ArchAbsPath(const std::string &path)
ARCH_API void ArchFileAdvise(FILE *file, int64_t offset, size_t count, ArchFileAdvice adv)
ARCH_API std::string ArchNormPath(const std::string &path, bool stripDriveSpecifier=false)
GLuint GLsizei GLsizei * length
Definition: glcorearb.h:795
ARCH_API ArchConstFileMapping ArchMapFileReadOnly(FILE *file, std::string *errMsg=nullptr)
std::unique_ptr< char const, Arch_Unmapper > ArchConstFileMapping
Definition: fileSystem.h:321
Arch_Unmapper(size_t length)
Definition: fileSystem.h:309
ARCH_API ArchMutableFileMapping ArchMapFileReadWrite(FILE *file, std::string *errMsg=nullptr)
ARCH_API const char * ArchGetTmpDir()
ARCH_API int ArchMakeTmpFile(const std::string &prefix, std::string *pathname=0)
GLintptr offset
Definition: glcorearb.h:665
std::unique_ptr< char, Arch_Unmapper > ArchMutableFileMapping
Definition: fileSystem.h:322
Definition: core.h:760
ARCH_API std::string ArchReadLink(const char *path)
ARCH_API int64_t ArchGetFileLength(const char *fileName)
size_t ArchGetFileMappingLength(ArchConstFileMapping const &m)
Return the length of an ArchConstFileMapping.
Definition: fileSystem.h:326
ARCH_API bool ArchGetStatMode(const char *pathname, int *mode)
GLenum mode
Definition: glcorearb.h:99
ARCH_API bool ArchStatIsWritable(const ArchStatType *st)
GLsizeiptr size
Definition: glcorearb.h:664
struct stat ArchStatType
Definition: fileSystem.h:120
ARCH_API bool ArchQueryMappedMemoryResidency(void const *addr, size_t len, unsigned char *pageMap)
GT_API const UT_StringHolder st
PXR_NAMESPACE_CLOSE_SCOPE PXR_NAMESPACE_OPEN_SCOPE
Definition: path.h:1432
#define ArchRmDir(path)
Definition: fileSystem.h:181
#define PXR_NAMESPACE_CLOSE_SCOPE
Definition: pxr.h:91
ARCH_API std::string ArchGetFileName(FILE *file)
#define ARCH_API
Definition: api.h:40
#define ArchFileAccess(path, mode)
Definition: fileSystem.h:157
ARCH_API int64_t ArchPRead(FILE *file, void *buffer, size_t count, int64_t offset)
ARCH_API void operator()(char *mapStart) const
size_t GetLength() const
Definition: fileSystem.h:312
ArchMemAdvice
Definition: fileSystem.h:364
ARCH_API std::string ArchMakeTmpSubdir(const std::string &tmpdir, const std::string &prefix)
ARCH_API int64_t ArchPWrite(FILE *file, void const *bytes, size_t count, int64_t offset)
GLint GLsizei count
Definition: glcorearb.h:405
Definition: format.h:2459
ARCH_API bool ArchGetModificationTime(const char *pathname, double *time)
ARCH_API std::string ArchMakeTmpFileName(const std::string &prefix, const std::string &suffix=std::string())