io_win32_unittest.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: laszlocsomor@google.com (Laszlo Csomor)
  31. //
  32. // Unit tests for long-path-aware open/mkdir/access/etc. on Windows, as well as
  33. // for the supporting utility functions.
  34. //
  35. // This file is only used on Windows, it's empty on other platforms.
  36. #if defined(_WIN32)
  37. #define WIN32_LEAN_AND_MEAN
  38. #include <errno.h>
  39. #include <fcntl.h>
  40. #include <stdlib.h>
  41. #include <string.h>
  42. #include <sys/stat.h>
  43. #include <sys/types.h>
  44. #include <wchar.h>
  45. #include <windows.h>
  46. #include <google/protobuf/stubs/io_win32.h>
  47. #include <gtest/gtest.h>
  48. #include <memory>
  49. #include <sstream>
  50. #include <string>
  51. namespace google {
  52. namespace protobuf {
  53. namespace internal {
  54. namespace win32 {
  55. namespace {
  56. const char kUtf8Text[] = {
  57. 'h', 'i', ' ',
  58. // utf-8: 11010000 10011111, utf-16: 100 0001 1111 = 0x041F
  59. 0xd0, 0x9f,
  60. // utf-8: 11010001 10000000, utf-16: 100 0100 0000 = 0x0440
  61. 0xd1, 0x80,
  62. // utf-8: 11010000 10111000, utf-16: 100 0011 1000 = 0x0438
  63. 0xd0, 0xb8,
  64. // utf-8: 11010000 10110010, utf-16: 100 0011 0010 = 0x0432
  65. 0xd0, 0xb2,
  66. // utf-8: 11010000 10110101, utf-16: 100 0011 0101 = 0x0435
  67. 0xd0, 0xb5,
  68. // utf-8: 11010001 10000010, utf-16: 100 0100 0010 = 0x0442
  69. 0xd1, 0x82, 0
  70. };
  71. const wchar_t kUtf16Text[] = {
  72. L'h', L'i', L' ',
  73. L'\x41f', L'\x440', L'\x438', L'\x432', L'\x435', L'\x442', 0
  74. };
  75. using std::string;
  76. using std::wstring;
  77. class IoWin32Test : public ::testing::Test {
  78. public:
  79. void SetUp();
  80. void TearDown();
  81. protected:
  82. bool CreateAllUnder(wstring path);
  83. bool DeleteAllUnder(wstring path);
  84. WCHAR working_directory[MAX_PATH];
  85. string test_tmpdir;
  86. wstring wtest_tmpdir;
  87. };
  88. #define ASSERT_INITIALIZED \
  89. { \
  90. EXPECT_FALSE(test_tmpdir.empty()); \
  91. EXPECT_FALSE(wtest_tmpdir.empty()); \
  92. }
  93. namespace {
  94. void StripTrailingSlashes(string* str) {
  95. int i = str->size() - 1;
  96. for (; i >= 0 && ((*str)[i] == '/' || (*str)[i] == '\\'); --i) {}
  97. str->resize(i+1);
  98. }
  99. bool GetEnvVarAsUtf8(const WCHAR* name, string* result) {
  100. DWORD size = ::GetEnvironmentVariableW(name, nullptr, 0);
  101. if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) {
  102. std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]);
  103. ::GetEnvironmentVariableW(name, wcs.get(), size);
  104. // GetEnvironmentVariableA retrieves an Active-Code-Page-encoded text which
  105. // we'd first need to convert to UTF-16 then to UTF-8, because there seems
  106. // to be no API function to do that conversion directly.
  107. // GetEnvironmentVariableW retrieves an UTF-16-encoded text, which we need
  108. // to convert to UTF-8.
  109. return strings::wcs_to_utf8(wcs.get(), result);
  110. } else {
  111. return false;
  112. }
  113. }
  114. bool GetCwdAsUtf8(string* result) {
  115. DWORD size = ::GetCurrentDirectoryW(0, nullptr);
  116. if (size > 0) {
  117. std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]);
  118. ::GetCurrentDirectoryW(size, wcs.get());
  119. // GetCurrentDirectoryA retrieves an Active-Code-Page-encoded text which
  120. // we'd first need to convert to UTF-16 then to UTF-8, because there seems
  121. // to be no API function to do that conversion directly.
  122. // GetCurrentDirectoryW retrieves an UTF-16-encoded text, which we need
  123. // to convert to UTF-8.
  124. return strings::wcs_to_utf8(wcs.get(), result);
  125. } else {
  126. return false;
  127. }
  128. }
  129. } // namespace
  130. void IoWin32Test::SetUp() {
  131. test_tmpdir.clear();
  132. wtest_tmpdir.clear();
  133. EXPECT_GT(::GetCurrentDirectoryW(MAX_PATH, working_directory), 0);
  134. string tmp;
  135. bool ok = false;
  136. if (!ok) {
  137. // Bazel sets this environment variable when it runs tests.
  138. ok = GetEnvVarAsUtf8(L"TEST_TMPDIR", &tmp);
  139. }
  140. if (!ok) {
  141. // Bazel 0.8.0 sets this environment for every build and test action.
  142. ok = GetEnvVarAsUtf8(L"TEMP", &tmp);
  143. }
  144. if (!ok) {
  145. // Bazel 0.8.0 sets this environment for every build and test action.
  146. ok = GetEnvVarAsUtf8(L"TMP", &tmp);
  147. }
  148. if (!ok) {
  149. // Fall back to using the current directory.
  150. ok = GetCwdAsUtf8(&tmp);
  151. }
  152. if (!ok || tmp.empty()) {
  153. FAIL() << "Cannot find a temp directory.";
  154. }
  155. StripTrailingSlashes(&tmp);
  156. std::stringstream result;
  157. // Deleting files and directories is asynchronous on Windows, and if TearDown
  158. // just deleted the previous temp directory, sometimes we cannot recreate the
  159. // same directory.
  160. // Use a counter so every test method gets its own temp directory.
  161. static unsigned int counter = 0;
  162. result << tmp << "\\w32tst" << counter++ << ".tmp";
  163. test_tmpdir = result.str();
  164. wtest_tmpdir = testonly_utf8_to_winpath(test_tmpdir.c_str());
  165. ASSERT_FALSE(wtest_tmpdir.empty());
  166. ASSERT_TRUE(DeleteAllUnder(wtest_tmpdir));
  167. ASSERT_TRUE(CreateAllUnder(wtest_tmpdir));
  168. }
  169. void IoWin32Test::TearDown() {
  170. if (!wtest_tmpdir.empty()) {
  171. DeleteAllUnder(wtest_tmpdir);
  172. }
  173. ::SetCurrentDirectoryW(working_directory);
  174. }
  175. bool IoWin32Test::CreateAllUnder(wstring path) {
  176. // Prepend UNC prefix if the path doesn't have it already. Don't bother
  177. // checking if the path is shorter than MAX_PATH, let's just do it
  178. // unconditionally.
  179. if (path.find(L"\\\\?\\") != 0) {
  180. path = wstring(L"\\\\?\\") + path;
  181. }
  182. if (::CreateDirectoryW(path.c_str(), nullptr) ||
  183. GetLastError() == ERROR_ALREADY_EXISTS ||
  184. GetLastError() == ERROR_ACCESS_DENIED) {
  185. return true;
  186. }
  187. if (GetLastError() == ERROR_PATH_NOT_FOUND) {
  188. size_t pos = path.find_last_of(L'\\');
  189. if (pos != wstring::npos) {
  190. wstring parent(path, 0, pos);
  191. if (CreateAllUnder(parent) && CreateDirectoryW(path.c_str(), nullptr)) {
  192. return true;
  193. }
  194. }
  195. }
  196. return false;
  197. }
  198. bool IoWin32Test::DeleteAllUnder(wstring path) {
  199. static const wstring kDot(L".");
  200. static const wstring kDotDot(L"..");
  201. // Prepend UNC prefix if the path doesn't have it already. Don't bother
  202. // checking if the path is shorter than MAX_PATH, let's just do it
  203. // unconditionally.
  204. if (path.find(L"\\\\?\\") != 0) {
  205. path = wstring(L"\\\\?\\") + path;
  206. }
  207. // Append "\" if necessary.
  208. if (path[path.size() - 1] != L'\\') {
  209. path.push_back(L'\\');
  210. }
  211. WIN32_FIND_DATAW metadata;
  212. HANDLE handle = ::FindFirstFileW((path + L"*").c_str(), &metadata);
  213. if (handle == INVALID_HANDLE_VALUE) {
  214. return true; // directory doesn't exist
  215. }
  216. bool result = true;
  217. do {
  218. wstring childname = metadata.cFileName;
  219. if (kDot != childname && kDotDot != childname) {
  220. wstring childpath = path + childname;
  221. if ((metadata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  222. // If this is not a junction, delete its contents recursively.
  223. // Finally delete this directory/junction too.
  224. if (((metadata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&
  225. !DeleteAllUnder(childpath)) ||
  226. !::RemoveDirectoryW(childpath.c_str())) {
  227. result = false;
  228. break;
  229. }
  230. } else {
  231. if (!::DeleteFileW(childpath.c_str())) {
  232. result = false;
  233. break;
  234. }
  235. }
  236. }
  237. } while (::FindNextFileW(handle, &metadata));
  238. ::FindClose(handle);
  239. return result;
  240. }
  241. TEST_F(IoWin32Test, AccessTest) {
  242. ASSERT_INITIALIZED;
  243. string path = test_tmpdir;
  244. while (path.size() < MAX_PATH - 30) {
  245. path += "\\accesstest";
  246. EXPECT_EQ(mkdir(path.c_str(), 0644), 0);
  247. }
  248. string file = path + "\\file.txt";
  249. int fd = open(file.c_str(), O_CREAT | O_WRONLY, 0644);
  250. if (fd > 0) {
  251. EXPECT_EQ(close(fd), 0);
  252. } else {
  253. EXPECT_TRUE(false);
  254. }
  255. EXPECT_EQ(access(test_tmpdir.c_str(), F_OK), 0);
  256. EXPECT_EQ(access(path.c_str(), F_OK), 0);
  257. EXPECT_EQ(access(path.c_str(), W_OK), 0);
  258. EXPECT_EQ(access(file.c_str(), F_OK | W_OK), 0);
  259. EXPECT_NE(access((file + ".blah").c_str(), F_OK), 0);
  260. EXPECT_NE(access((file + ".blah").c_str(), W_OK), 0);
  261. EXPECT_EQ(access(".", F_OK), 0);
  262. EXPECT_EQ(access(".", W_OK), 0);
  263. EXPECT_EQ(access((test_tmpdir + "/accesstest").c_str(), F_OK | W_OK), 0);
  264. ASSERT_EQ(access((test_tmpdir + "/./normalize_me/.././accesstest").c_str(),
  265. F_OK | W_OK),
  266. 0);
  267. EXPECT_NE(access("io_win32_unittest.AccessTest.nonexistent", F_OK), 0);
  268. EXPECT_NE(access("io_win32_unittest.AccessTest.nonexistent", W_OK), 0);
  269. ASSERT_EQ(access("c:bad", F_OK), -1);
  270. ASSERT_EQ(errno, ENOENT);
  271. ASSERT_EQ(access("/tmp/bad", F_OK), -1);
  272. ASSERT_EQ(errno, ENOENT);
  273. ASSERT_EQ(access("\\bad", F_OK), -1);
  274. ASSERT_EQ(errno, ENOENT);
  275. }
  276. TEST_F(IoWin32Test, OpenTest) {
  277. ASSERT_INITIALIZED;
  278. string path = test_tmpdir;
  279. while (path.size() < MAX_PATH) {
  280. path += "\\opentest";
  281. EXPECT_EQ(mkdir(path.c_str(), 0644), 0);
  282. }
  283. string file = path + "\\file.txt";
  284. int fd = open(file.c_str(), O_CREAT | O_WRONLY, 0644);
  285. if (fd > 0) {
  286. EXPECT_EQ(write(fd, "hello", 5), 5);
  287. EXPECT_EQ(close(fd), 0);
  288. } else {
  289. EXPECT_TRUE(false);
  290. }
  291. ASSERT_EQ(open("c:bad.txt", O_CREAT | O_WRONLY, 0644), -1);
  292. ASSERT_EQ(errno, ENOENT);
  293. ASSERT_EQ(open("/tmp/bad.txt", O_CREAT | O_WRONLY, 0644), -1);
  294. ASSERT_EQ(errno, ENOENT);
  295. ASSERT_EQ(open("\\bad.txt", O_CREAT | O_WRONLY, 0644), -1);
  296. ASSERT_EQ(errno, ENOENT);
  297. }
  298. TEST_F(IoWin32Test, MkdirTest) {
  299. ASSERT_INITIALIZED;
  300. string path = test_tmpdir;
  301. do {
  302. path += "\\mkdirtest";
  303. ASSERT_EQ(mkdir(path.c_str(), 0644), 0);
  304. } while (path.size() <= MAX_PATH);
  305. ASSERT_EQ(mkdir("c:bad", 0644), -1);
  306. ASSERT_EQ(errno, ENOENT);
  307. ASSERT_EQ(mkdir("/tmp/bad", 0644), -1);
  308. ASSERT_EQ(errno, ENOENT);
  309. ASSERT_EQ(mkdir("\\bad", 0644), -1);
  310. ASSERT_EQ(errno, ENOENT);
  311. }
  312. TEST_F(IoWin32Test, MkdirTestNonAscii) {
  313. ASSERT_INITIALIZED;
  314. // Create a non-ASCII path.
  315. // Ensure that we can create the directory using SetCurrentDirectoryW.
  316. EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), nullptr));
  317. EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), nullptr));
  318. // Ensure that we can create a very similarly named directory using mkdir.
  319. // We don't attemp to delete and recreate the same directory, because on
  320. // Windows, deleting files and directories seems to be asynchronous.
  321. EXPECT_EQ(mkdir((test_tmpdir + "\\2").c_str(), 0644), 0);
  322. EXPECT_EQ(mkdir((test_tmpdir + "\\2\\" + kUtf8Text).c_str(), 0644), 0);
  323. }
  324. TEST_F(IoWin32Test, ChdirTest) {
  325. string path("C:\\");
  326. EXPECT_EQ(access(path.c_str(), F_OK), 0);
  327. ASSERT_EQ(chdir(path.c_str()), 0);
  328. // Do not try to chdir into the test_tmpdir, it may already contain directory
  329. // names with trailing dots.
  330. // Instead test here with an obviously dot-trailed path. If the win32_chdir
  331. // function would not convert the path to absolute and prefix with "\\?\" then
  332. // the Win32 API would ignore the trailing dot, but because of the prefixing
  333. // there'll be no path processing done, so we'll actually attempt to chdir
  334. // into "C:\some\path\foo."
  335. path = test_tmpdir + "/foo.";
  336. EXPECT_EQ(mkdir(path.c_str(), 644), 0);
  337. EXPECT_EQ(access(path.c_str(), F_OK), 0);
  338. ASSERT_NE(chdir(path.c_str()), 0);
  339. }
  340. TEST_F(IoWin32Test, ChdirTestNonAscii) {
  341. ASSERT_INITIALIZED;
  342. // Create a directory with a non-ASCII path and ensure we can cd into it.
  343. wstring wNonAscii(wtest_tmpdir + L"\\" + kUtf16Text);
  344. string nonAscii;
  345. EXPECT_TRUE(strings::wcs_to_utf8(wNonAscii.c_str(), &nonAscii));
  346. EXPECT_TRUE(CreateDirectoryW(wNonAscii.c_str(), nullptr));
  347. WCHAR cwd[MAX_PATH];
  348. EXPECT_TRUE(GetCurrentDirectoryW(MAX_PATH, cwd));
  349. // Ensure that we can cd into the path using SetCurrentDirectoryW.
  350. EXPECT_TRUE(SetCurrentDirectoryW(wNonAscii.c_str()));
  351. EXPECT_TRUE(SetCurrentDirectoryW(cwd));
  352. // Ensure that we can cd into the path using chdir.
  353. ASSERT_EQ(chdir(nonAscii.c_str()), 0);
  354. // Ensure that the GetCurrentDirectoryW returns the desired path.
  355. EXPECT_TRUE(GetCurrentDirectoryW(MAX_PATH, cwd));
  356. ASSERT_EQ(wNonAscii, cwd);
  357. }
  358. TEST_F(IoWin32Test, AsWindowsPathTest) {
  359. DWORD size = GetCurrentDirectoryW(0, nullptr);
  360. std::unique_ptr<wchar_t[]> cwd_str(new wchar_t[size]);
  361. EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0);
  362. wstring cwd = wstring(L"\\\\?\\") + cwd_str.get();
  363. ASSERT_EQ(testonly_utf8_to_winpath("relative_mkdirtest"),
  364. cwd + L"\\relative_mkdirtest");
  365. ASSERT_EQ(testonly_utf8_to_winpath("preserve//\\trailing///"),
  366. cwd + L"\\preserve\\trailing\\");
  367. ASSERT_EQ(testonly_utf8_to_winpath("./normalize_me\\/../blah"),
  368. cwd + L"\\blah");
  369. std::ostringstream relpath;
  370. for (wchar_t* p = cwd_str.get(); *p; ++p) {
  371. if (*p == '/' || *p == '\\') {
  372. relpath << "../";
  373. }
  374. }
  375. relpath << ".\\/../\\./beyond-toplevel";
  376. ASSERT_EQ(testonly_utf8_to_winpath(relpath.str().c_str()),
  377. wstring(L"\\\\?\\") + cwd_str.get()[0] + L":\\beyond-toplevel");
  378. // Absolute unix paths lack drive letters, driveless absolute windows paths
  379. // do too. Neither can be converted to a drive-specifying absolute Windows
  380. // path.
  381. ASSERT_EQ(testonly_utf8_to_winpath("/absolute/unix/path"), L"");
  382. // Though valid on Windows, we also don't support UNC paths (\\UNC\\blah).
  383. ASSERT_EQ(testonly_utf8_to_winpath("\\driveless\\absolute"), L"");
  384. // Though valid in cmd.exe, drive-relative paths are not supported.
  385. ASSERT_EQ(testonly_utf8_to_winpath("c:foo"), L"");
  386. ASSERT_EQ(testonly_utf8_to_winpath("c:/foo"), L"\\\\?\\c:\\foo");
  387. ASSERT_EQ(testonly_utf8_to_winpath("\\\\?\\C:\\foo"), L"\\\\?\\C:\\foo");
  388. }
  389. TEST_F(IoWin32Test, Utf8Utf16ConversionTest) {
  390. string mbs;
  391. wstring wcs;
  392. ASSERT_TRUE(strings::utf8_to_wcs(kUtf8Text, &wcs));
  393. ASSERT_TRUE(strings::wcs_to_utf8(kUtf16Text, &mbs));
  394. ASSERT_EQ(wcs, kUtf16Text);
  395. ASSERT_EQ(mbs, kUtf8Text);
  396. }
  397. } // namespace
  398. } // namespace win32
  399. } // namespace internal
  400. } // namespace protobuf
  401. } // namespace google
  402. #endif // defined(_WIN32)