PageRenderTime 30ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/qmake/library/ioutils.cpp

https://gitlab.com/f3822/qtbase
C++ | 339 lines | 274 code | 21 blank | 44 comment | 48 complexity | e58572a6ebb18e54c9d551bcac77fbc2 MD5 | raw file
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2016 The Qt Company Ltd.
  4. ** Contact: https://www.qt.io/licensing/
  5. **
  6. ** This file is part of the qmake application of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:GPL-EXCEPT$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and The Qt Company. For licensing terms
  14. ** and conditions see https://www.qt.io/terms-conditions. For further
  15. ** information use the contact form at https://www.qt.io/contact-us.
  16. **
  17. ** GNU General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU
  19. ** General Public License version 3 as published by the Free Software
  20. ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
  21. ** included in the packaging of this file. Please review the following
  22. ** information to ensure the GNU General Public License requirements will
  23. ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
  24. **
  25. ** $QT_END_LICENSE$
  26. **
  27. ****************************************************************************/
  28. #include "ioutils.h"
  29. #include <qdir.h>
  30. #include <qfile.h>
  31. #include <qregularexpression.h>
  32. #ifdef Q_OS_WIN
  33. # include <qt_windows.h>
  34. #else
  35. # include <sys/types.h>
  36. # include <sys/stat.h>
  37. # include <unistd.h>
  38. # include <utime.h>
  39. # include <fcntl.h>
  40. # include <errno.h>
  41. #endif
  42. #define fL1S(s) QString::fromLatin1(s)
  43. QT_BEGIN_NAMESPACE
  44. using namespace QMakeInternal;
  45. QString IoUtils::binaryAbsLocation(const QString &argv0)
  46. {
  47. QString ret;
  48. if (!argv0.isEmpty() && isAbsolutePath(argv0)) {
  49. ret = argv0;
  50. } else if (argv0.contains(QLatin1Char('/'))
  51. #ifdef Q_OS_WIN
  52. || argv0.contains(QLatin1Char('\\'))
  53. #endif
  54. ) { // relative PWD
  55. ret = QDir::current().absoluteFilePath(argv0);
  56. } else { // in the PATH
  57. QByteArray pEnv = qgetenv("PATH");
  58. QDir currentDir = QDir::current();
  59. #ifdef Q_OS_WIN
  60. QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(";"));
  61. paths.prepend(QLatin1String("."));
  62. #else
  63. QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(":"));
  64. #endif
  65. for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
  66. if ((*p).isEmpty())
  67. continue;
  68. QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
  69. if (QFile::exists(candidate)) {
  70. ret = candidate;
  71. break;
  72. }
  73. }
  74. }
  75. return QDir::cleanPath(ret);
  76. }
  77. IoUtils::FileType IoUtils::fileType(const QString &fileName)
  78. {
  79. Q_ASSERT(fileName.isEmpty() || isAbsolutePath(fileName));
  80. #ifdef Q_OS_WIN
  81. DWORD attr = GetFileAttributesW((WCHAR*)fileName.utf16());
  82. if (attr == INVALID_FILE_ATTRIBUTES)
  83. return FileNotFound;
  84. return (attr & FILE_ATTRIBUTE_DIRECTORY) ? FileIsDir : FileIsRegular;
  85. #else
  86. struct ::stat st;
  87. if (::stat(fileName.toLocal8Bit().constData(), &st))
  88. return FileNotFound;
  89. return S_ISDIR(st.st_mode) ? FileIsDir : S_ISREG(st.st_mode) ? FileIsRegular : FileNotFound;
  90. #endif
  91. }
  92. bool IoUtils::isRelativePath(const QString &path)
  93. {
  94. #ifdef QMAKE_BUILTIN_PRFS
  95. if (path.startsWith(QLatin1String(":/")))
  96. return false;
  97. #endif
  98. #ifdef Q_OS_WIN
  99. // Unlike QFileInfo, this considers only paths with both a drive prefix and
  100. // a subsequent (back-)slash absolute:
  101. if (path.length() >= 3 && path.at(1) == QLatin1Char(':') && path.at(0).isLetter()
  102. && (path.at(2) == QLatin1Char('/') || path.at(2) == QLatin1Char('\\'))) {
  103. return false;
  104. }
  105. // ... unless, of course, they're UNC:
  106. if (path.length() >= 2
  107. && (path.at(0).unicode() == '\\' || path.at(0).unicode() == '/')
  108. && path.at(1) == path.at(0)) {
  109. return false;
  110. }
  111. #else
  112. if (path.startsWith(QLatin1Char('/')))
  113. return false;
  114. #endif // Q_OS_WIN
  115. return true;
  116. }
  117. QStringView IoUtils::pathName(const QString &fileName)
  118. {
  119. return QStringView{fileName}.left(fileName.lastIndexOf(QLatin1Char('/')) + 1);
  120. }
  121. QStringView IoUtils::fileName(const QString &fileName)
  122. {
  123. return QStringView(fileName).mid(fileName.lastIndexOf(QLatin1Char('/')) + 1);
  124. }
  125. QString IoUtils::resolvePath(const QString &baseDir, const QString &fileName)
  126. {
  127. if (fileName.isEmpty())
  128. return QString();
  129. if (isAbsolutePath(fileName))
  130. return QDir::cleanPath(fileName);
  131. #ifdef Q_OS_WIN // Add drive to otherwise-absolute path:
  132. if (fileName.at(0).unicode() == '/' || fileName.at(0).unicode() == '\\') {
  133. Q_ASSERT_X(isAbsolutePath(baseDir), "IoUtils::resolvePath", qUtf8Printable(baseDir));
  134. return QDir::cleanPath(baseDir.left(2) + fileName);
  135. }
  136. #endif // Q_OS_WIN
  137. return QDir::cleanPath(baseDir + QLatin1Char('/') + fileName);
  138. }
  139. inline static
  140. bool isSpecialChar(ushort c, const uchar (&iqm)[16])
  141. {
  142. if ((c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7))))
  143. return true;
  144. return false;
  145. }
  146. inline static
  147. bool hasSpecialChars(const QString &arg, const uchar (&iqm)[16])
  148. {
  149. for (int x = arg.length() - 1; x >= 0; --x) {
  150. if (isSpecialChar(arg.unicode()[x].unicode(), iqm))
  151. return true;
  152. }
  153. return false;
  154. }
  155. QString IoUtils::shellQuoteUnix(const QString &arg)
  156. {
  157. // Chars that should be quoted (TM). This includes:
  158. static const uchar iqm[] = {
  159. 0xff, 0xff, 0xff, 0xff, 0xdf, 0x07, 0x00, 0xd8,
  160. 0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x78
  161. }; // 0-32 \'"$`<>|;&(){}*?#!~[]
  162. if (!arg.length())
  163. return QString::fromLatin1("''");
  164. QString ret(arg);
  165. if (hasSpecialChars(ret, iqm)) {
  166. ret.replace(QLatin1Char('\''), QLatin1String("'\\''"));
  167. ret.prepend(QLatin1Char('\''));
  168. ret.append(QLatin1Char('\''));
  169. }
  170. return ret;
  171. }
  172. QString IoUtils::shellQuoteWin(const QString &arg)
  173. {
  174. // Chars that should be quoted (TM). This includes:
  175. // - control chars & space
  176. // - the shell meta chars "&()<>^|
  177. // - the potential separators ,;=
  178. static const uchar iqm[] = {
  179. 0xff, 0xff, 0xff, 0xff, 0x45, 0x13, 0x00, 0x78,
  180. 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
  181. };
  182. // Shell meta chars that need escaping.
  183. static const uchar ism[] = {
  184. 0x00, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x50,
  185. 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
  186. }; // &()<>^|
  187. if (!arg.length())
  188. return QString::fromLatin1("\"\"");
  189. QString ret(arg);
  190. if (hasSpecialChars(ret, iqm)) {
  191. // The process-level standard quoting allows escaping quotes with backslashes (note
  192. // that backslashes don't escape themselves, unless they are followed by a quote).
  193. // Consequently, quotes are escaped and their preceding backslashes are doubled.
  194. ret.replace(QRegularExpression(QLatin1String("(\\\\*)\"")), QLatin1String("\\1\\1\\\""));
  195. // Trailing backslashes must be doubled as well, as they are followed by a quote.
  196. ret.replace(QRegularExpression(QLatin1String("(\\\\+)$")), QLatin1String("\\1\\1"));
  197. // However, the shell also interprets the command, and no backslash-escaping exists
  198. // there - a quote always toggles the quoting state, but is nonetheless passed down
  199. // to the called process verbatim. In the unquoted state, the circumflex escapes
  200. // meta chars (including itself and quotes), and is removed from the command.
  201. bool quoted = true;
  202. for (int i = 0; i < ret.length(); i++) {
  203. QChar c = ret.unicode()[i];
  204. if (c.unicode() == '"')
  205. quoted = !quoted;
  206. else if (!quoted && isSpecialChar(c.unicode(), ism))
  207. ret.insert(i++, QLatin1Char('^'));
  208. }
  209. if (!quoted)
  210. ret.append(QLatin1Char('^'));
  211. ret.append(QLatin1Char('"'));
  212. ret.prepend(QLatin1Char('"'));
  213. }
  214. return ret;
  215. }
  216. #if defined(PROEVALUATOR_FULL)
  217. # if defined(Q_OS_WIN)
  218. static QString windowsErrorCode()
  219. {
  220. wchar_t *string = nullptr;
  221. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
  222. NULL,
  223. GetLastError(),
  224. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  225. (LPWSTR)&string,
  226. 0,
  227. NULL);
  228. QString ret = QString::fromWCharArray(string);
  229. LocalFree((HLOCAL)string);
  230. return ret.trimmed();
  231. }
  232. # endif
  233. bool IoUtils::touchFile(const QString &targetFileName, const QString &referenceFileName, QString *errorString)
  234. {
  235. # ifdef Q_OS_UNIX
  236. struct stat st;
  237. if (stat(referenceFileName.toLocal8Bit().constData(), &st)) {
  238. *errorString = fL1S("Cannot stat() reference file %1: %2.").arg(referenceFileName, fL1S(strerror(errno)));
  239. return false;
  240. }
  241. # if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L
  242. const struct timespec times[2] = { { 0, UTIME_NOW }, st.st_mtim };
  243. const bool utimeError = utimensat(AT_FDCWD, targetFileName.toLocal8Bit().constData(), times, 0) < 0;
  244. # else
  245. struct utimbuf utb;
  246. utb.actime = time(0);
  247. utb.modtime = st.st_mtime;
  248. const bool utimeError= utime(targetFileName.toLocal8Bit().constData(), &utb) < 0;
  249. # endif
  250. if (utimeError) {
  251. *errorString = fL1S("Cannot touch %1: %2.").arg(targetFileName, fL1S(strerror(errno)));
  252. return false;
  253. }
  254. # else
  255. HANDLE rHand = CreateFile((wchar_t*)referenceFileName.utf16(),
  256. GENERIC_READ, FILE_SHARE_READ,
  257. NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  258. if (rHand == INVALID_HANDLE_VALUE) {
  259. *errorString = fL1S("Cannot open reference file %1: %2").arg(referenceFileName, windowsErrorCode());
  260. return false;
  261. }
  262. FILETIME ft;
  263. GetFileTime(rHand, NULL, NULL, &ft);
  264. CloseHandle(rHand);
  265. HANDLE wHand = CreateFile((wchar_t*)targetFileName.utf16(),
  266. GENERIC_WRITE, FILE_SHARE_READ,
  267. NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  268. if (wHand == INVALID_HANDLE_VALUE) {
  269. *errorString = fL1S("Cannot open %1: %2").arg(targetFileName, windowsErrorCode());
  270. return false;
  271. }
  272. SetFileTime(wHand, NULL, NULL, &ft);
  273. CloseHandle(wHand);
  274. # endif
  275. return true;
  276. }
  277. #if defined(QT_BUILD_QMAKE) && defined(Q_OS_UNIX)
  278. bool IoUtils::readLinkTarget(const QString &symlinkPath, QString *target)
  279. {
  280. const QByteArray localSymlinkPath = QFile::encodeName(symlinkPath);
  281. # if defined(__GLIBC__) && !defined(PATH_MAX)
  282. # define PATH_CHUNK_SIZE 256
  283. char *s = 0;
  284. int len = -1;
  285. int size = PATH_CHUNK_SIZE;
  286. forever {
  287. s = (char *)::realloc(s, size);
  288. len = ::readlink(localSymlinkPath.constData(), s, size);
  289. if (len < 0) {
  290. ::free(s);
  291. break;
  292. }
  293. if (len < size)
  294. break;
  295. size *= 2;
  296. }
  297. # else
  298. char s[PATH_MAX+1];
  299. int len = readlink(localSymlinkPath.constData(), s, PATH_MAX);
  300. # endif
  301. if (len <= 0)
  302. return false;
  303. *target = QFile::decodeName(QByteArray(s, len));
  304. # if defined(__GLIBC__) && !defined(PATH_MAX)
  305. ::free(s);
  306. # endif
  307. return true;
  308. }
  309. #endif
  310. #endif // PROEVALUATOR_FULL
  311. QT_END_NAMESPACE