ResidualVM logo ResidualVM website - Forums - Contact us BuildBot - Doxygen - Wiki curved edge

posix-fs.cpp

Go to the documentation of this file.
00001 /* ScummVM - Graphic Adventure Engine
00002  *
00003  * ScummVM is the legal property of its developers, whose names
00004  * are too numerous to list here. Please refer to the COPYRIGHT
00005  * file distributed with this source distribution.
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation; either version 2
00010  * of the License, or (at your option) any later version.
00011  *
00012  * This program is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  * GNU General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00020  *
00021  */
00022 
00023 #if defined(POSIX) || defined(PLAYSTATION3) || defined(PSP2)
00024 
00025 // Re-enable some forbidden symbols to avoid clashes with stat.h and unistd.h.
00026 // Also with clock() in sys/time.h in some Mac OS X SDKs.
00027 #define FORBIDDEN_SYMBOL_EXCEPTION_time_h
00028 #define FORBIDDEN_SYMBOL_EXCEPTION_unistd_h
00029 #define FORBIDDEN_SYMBOL_EXCEPTION_mkdir
00030 #define FORBIDDEN_SYMBOL_EXCEPTION_getenv
00031 #define FORBIDDEN_SYMBOL_EXCEPTION_exit     //Needed for IRIX's unistd.h
00032 #define FORBIDDEN_SYMBOL_EXCEPTION_random
00033 #define FORBIDDEN_SYMBOL_EXCEPTION_srandom
00034 
00035 #include "backends/fs/posix/posix-fs.h"
00036 #include "backends/fs/stdiostream.h"
00037 #include "common/algorithm.h"
00038 
00039 #include <sys/param.h>
00040 #include <sys/stat.h>
00041 #ifdef PSP2
00042 #include "backends/fs/psp2/psp2-dirent.h"
00043 #define mkdir sceIoMkdir
00044 #else
00045 #include <dirent.h>
00046 #endif
00047 #include <stdio.h>
00048 #include <errno.h>
00049 #include <fcntl.h>
00050 
00051 #ifdef __OS2__
00052 #define INCL_DOS
00053 #include <os2.h>
00054 #endif
00055 
00056 
00057 void POSIXFilesystemNode::setFlags() {
00058     struct stat st;
00059 
00060     _isValid = (0 == stat(_path.c_str(), &st));
00061     _isDirectory = _isValid ? S_ISDIR(st.st_mode) : false;
00062 }
00063 
00064 POSIXFilesystemNode::POSIXFilesystemNode(const Common::String &p) {
00065     assert(p.size() > 0);
00066 
00067 #ifdef PSP2
00068     if (p == "/") {
00069         _isDirectory = true;
00070         _isValid = false;
00071         _path = p;
00072         _displayName = p;
00073         return;
00074     }
00075 #endif
00076 
00077     // Expand "~/" to the value of the HOME env variable
00078     if (p.hasPrefix("~/")) {
00079         const char *home = getenv("HOME");
00080         if (home != NULL && strlen(home) < MAXPATHLEN) {
00081             _path = home;
00082             // Skip over the tilda.  We know that p contains at least
00083             // two chars, so this is safe:
00084             _path += p.c_str() + 1;
00085         }
00086     } else {
00087         _path = p;
00088     }
00089 
00090 #ifdef __OS2__
00091     // On OS/2, 'X:/' is a root of drive X, so we should not remove that last
00092     // slash.
00093     if (!(_path.size() == 3 && _path.hasSuffix(":/")))
00094 #endif
00095     // Normalize the path (that is, remove unneeded slashes etc.)
00096     _path = Common::normalizePath(_path, '/');
00097     _displayName = Common::lastPathComponent(_path, '/');
00098 
00099     // TODO: should we turn relative paths into absolute ones?
00100     // Pro: Ensures the "getParent" works correctly even for relative dirs.
00101     // Contra: The user may wish to use (and keep!) relative paths in his
00102     //   config file, and converting relative to absolute paths may hurt him...
00103     //
00104     // An alternative approach would be to change getParent() to work correctly
00105     // if "_path" is the empty string.
00106 #if 0
00107     if (!_path.hasPrefix("/")) {
00108         char buf[MAXPATHLEN+1];
00109         getcwd(buf, MAXPATHLEN);
00110         strcat(buf, "/");
00111         _path = buf + _path;
00112     }
00113 #endif
00114     // TODO: Should we enforce that the path is absolute at this point?
00115     //assert(_path.hasPrefix("/"));
00116 
00117     setFlags();
00118 }
00119 
00120 AbstractFSNode *POSIXFilesystemNode::getChild(const Common::String &n) const {
00121     assert(!_path.empty());
00122     assert(_isDirectory);
00123 
00124     // Make sure the string contains no slashes
00125     assert(!n.contains('/'));
00126 
00127     // We assume here that _path is already normalized (hence don't bother to call
00128     //  Common::normalizePath on the final path).
00129     Common::String newPath(_path);
00130     if (_path.lastChar() != '/')
00131         newPath += '/';
00132     newPath += n;
00133 
00134     return makeNode(newPath);
00135 }
00136 
00137 bool POSIXFilesystemNode::getChildren(AbstractFSList &myList, ListMode mode, bool hidden) const {
00138     assert(_isDirectory);
00139 
00140 #ifdef __OS2__
00141     if (_path == "/") {
00142         // Special case for the root dir: List all DOS drives
00143         ULONG ulDrvNum;
00144         ULONG ulDrvMap;
00145 
00146         DosQueryCurrentDisk(&ulDrvNum, &ulDrvMap);
00147 
00148         for (int i = 0; i < 26; i++) {
00149             if (ulDrvMap & 1) {
00150                 char drive_root[] = "A:/";
00151                 drive_root[0] += i;
00152 
00153                 POSIXFilesystemNode *entry = new POSIXFilesystemNode();
00154                 entry->_isDirectory = true;
00155                 entry->_isValid = true;
00156                 entry->_path = drive_root;
00157                 entry->_displayName = "[" + Common::String(drive_root, 2) + "]";
00158                 myList.push_back(entry);
00159             }
00160 
00161             ulDrvMap >>= 1;
00162         }
00163 
00164         return true;
00165     }
00166 #endif
00167 #ifdef PSP2
00168     if (_path == "/") {
00169         POSIXFilesystemNode *entry1 = new POSIXFilesystemNode("ux0:");
00170         myList.push_back(entry1);
00171         POSIXFilesystemNode *entry2 = new POSIXFilesystemNode("uma0:");
00172         myList.push_back(entry2);
00173         return true;
00174     }
00175 #endif
00176 
00177     DIR *dirp = opendir(_path.c_str());
00178     struct dirent *dp;
00179 
00180     if (dirp == NULL)
00181         return false;
00182 
00183     // loop over dir entries using readdir
00184     while ((dp = readdir(dirp)) != NULL) {
00185         // Skip 'invisible' files if necessary
00186         if (dp->d_name[0] == '.' && !hidden) {
00187             continue;
00188         }
00189         // Skip '.' and '..' to avoid cycles
00190         if ((dp->d_name[0] == '.' && dp->d_name[1] == 0) || (dp->d_name[0] == '.' && dp->d_name[1] == '.')) {
00191             continue;
00192         }
00193 
00194         // Start with a clone of this node, with the correct path set
00195         POSIXFilesystemNode entry(*this);
00196         entry._displayName = dp->d_name;
00197         if (_path.lastChar() != '/')
00198             entry._path += '/';
00199         entry._path += entry._displayName;
00200 
00201 #if defined(SYSTEM_NOT_SUPPORTING_D_TYPE)
00202         /* TODO: d_type is not part of POSIX, so it might not be supported
00203          * on some of our targets. For those systems where it isn't supported,
00204          * add this #elif case, which tries to use stat() instead.
00205          *
00206          * The d_type method is used to avoid costly recurrent stat() calls in big
00207          * directories.
00208          */
00209         entry.setFlags();
00210 #else
00211         if (dp->d_type == DT_UNKNOWN) {
00212             // Fall back to stat()
00213             entry.setFlags();
00214         } else {
00215             entry._isValid = (dp->d_type == DT_DIR) || (dp->d_type == DT_REG) || (dp->d_type == DT_LNK);
00216             if (dp->d_type == DT_LNK) {
00217                 struct stat st;
00218                 if (stat(entry._path.c_str(), &st) == 0)
00219                     entry._isDirectory = S_ISDIR(st.st_mode);
00220                 else
00221                     entry._isDirectory = false;
00222             } else {
00223                 entry._isDirectory = (dp->d_type == DT_DIR);
00224             }
00225         }
00226 #endif
00227 
00228         // Skip files that are invalid for some reason (e.g. because we couldn't
00229         // properly stat them).
00230         if (!entry._isValid)
00231             continue;
00232 
00233         // Honor the chosen mode
00234         if ((mode == Common::FSNode::kListFilesOnly && entry._isDirectory) ||
00235             (mode == Common::FSNode::kListDirectoriesOnly && !entry._isDirectory))
00236             continue;
00237 
00238         myList.push_back(new POSIXFilesystemNode(entry));
00239     }
00240     closedir(dirp);
00241 
00242     return true;
00243 }
00244 
00245 AbstractFSNode *POSIXFilesystemNode::getParent() const {
00246     if (_path == "/")
00247         return 0;   // The filesystem root has no parent
00248 
00249 #ifdef __OS2__
00250     if (_path.size() == 3 && _path.hasSuffix(":/"))
00251         // This is a root directory of a drive
00252         return makeNode("/");   // return a virtual root for a list of drives
00253 #endif
00254 #ifdef PSP2
00255     if (_path.hasSuffix(":"))
00256         return makeNode("/");
00257 #endif
00258 
00259     const char *start = _path.c_str();
00260     const char *end = start + _path.size();
00261 
00262     // Strip of the last component. We make use of the fact that at this
00263     // point, _path is guaranteed to be normalized
00264     while (end > start && *(end-1) != '/')
00265         end--;
00266 
00267     if (end == start) {
00268         // This only happens if we were called with a relative path, for which
00269         // there simply is no parent.
00270         // TODO: We could also resolve this by assuming that the parent is the
00271         //       current working directory, and returning a node referring to that.
00272         return 0;
00273     }
00274 
00275     return makeNode(Common::String(start, end));
00276 }
00277 
00278 Common::SeekableReadStream *POSIXFilesystemNode::createReadStream() {
00279     return StdioStream::makeFromPath(getPath(), false);
00280 }
00281 
00282 Common::WriteStream *POSIXFilesystemNode::createWriteStream() {
00283     return StdioStream::makeFromPath(getPath(), true);
00284 }
00285 
00286 bool POSIXFilesystemNode::create(bool isDirectoryFlag) {
00287     bool success;
00288 
00289     if (isDirectoryFlag) {
00290         success = mkdir(_path.c_str(), 0755) == 0;
00291     } else {
00292         int fd = open(_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0755);
00293         success = fd >= 0;
00294 
00295         if (fd >= 0) {
00296             close(fd);
00297         }
00298     }
00299 
00300     if (success) {
00301         setFlags();
00302         if (_isValid) {
00303             if (_isDirectory != isDirectoryFlag) warning("failed to create %s: got %s", isDirectoryFlag ? "directory" : "file", _isDirectory ? "directory" : "file");
00304             return _isDirectory == isDirectoryFlag;
00305         }
00306 
00307         warning("POSIXFilesystemNode: %s() was a success, but stat indicates there is no such %s",
00308             isDirectoryFlag ? "mkdir" : "creat", isDirectoryFlag ? "directory" : "file");
00309         return false;
00310     }
00311 
00312     return false;
00313 }
00314 
00315 namespace Posix {
00316 
00317 bool assureDirectoryExists(const Common::String &dir, const char *prefix) {
00318     struct stat sb;
00319 
00320     // Check whether the prefix exists if one is supplied.
00321     if (prefix) {
00322         if (stat(prefix, &sb) != 0) {
00323             return false;
00324         } else if (!S_ISDIR(sb.st_mode)) {
00325             return false;
00326         }
00327     }
00328 
00329     // Obtain absolute path.
00330     Common::String path;
00331     if (prefix) {
00332         path = prefix;
00333         path += '/';
00334         path += dir;
00335     } else {
00336         path = dir;
00337     }
00338 
00339     path = Common::normalizePath(path, '/');
00340 
00341     const Common::String::iterator end = path.end();
00342     Common::String::iterator cur = path.begin();
00343     if (*cur == '/')
00344         ++cur;
00345 
00346     do {
00347         if (cur + 1 != end) {
00348             if (*cur != '/') {
00349                 continue;
00350             }
00351 
00352             // It is kind of ugly and against the purpose of Common::String to
00353             // insert 0s inside, but this is just for a local string and
00354             // simplifies the code a lot.
00355             *cur = '\0';
00356         }
00357 
00358         if (mkdir(path.c_str(), 0755) != 0) {
00359             if (errno == EEXIST) {
00360                 if (stat(path.c_str(), &sb) != 0) {
00361                     return false;
00362                 } else if (!S_ISDIR(sb.st_mode)) {
00363                     return false;
00364                 }
00365             } else {
00366                 return false;
00367             }
00368         }
00369 
00370         *cur = '/';
00371     } while (cur++ != end);
00372 
00373     return true;
00374 }
00375 
00376 } // End of namespace Posix
00377 
00378 #endif //#if defined(POSIX)


Generated on Sat Mar 16 2019 05:01:50 for ResidualVM by doxygen 1.7.1
curved edge   curved edge