1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "sysdeps/stat.h"
18
19 #include <errno.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <string>
25
26 #include <android-base/utf8.h>
27
28 // Version of stat() that takes a UTF-8 path.
adb_stat(const char * path,struct adb_stat * s)29 int adb_stat(const char* path, struct adb_stat* s) {
30 // This definition of wstat seems to be missing from <sys/stat.h>.
31 #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
32 #ifdef _USE_32BIT_TIME_T
33 #define wstat _wstat32i64
34 #else
35 #define wstat _wstat64
36 #endif
37 #else
38 // <sys/stat.h> has a function prototype for wstat() that should be available.
39 #endif
40
41 std::wstring path_wide;
42 if (!android::base::UTF8ToWide(path, &path_wide)) {
43 errno = ENOENT;
44 return -1;
45 }
46
47 // If the path has a trailing slash, stat will fail with ENOENT regardless of whether the path
48 // is a directory or not.
49 bool expected_directory = false;
50 while (*path_wide.rbegin() == u'/' || *path_wide.rbegin() == u'\\') {
51 path_wide.pop_back();
52 expected_directory = true;
53 }
54
55 struct adb_stat st;
56 int result = wstat(path_wide.c_str(), &st);
57 if (result == 0 && expected_directory) {
58 if (!S_ISDIR(st.st_mode)) {
59 errno = ENOTDIR;
60 return -1;
61 }
62 }
63
64 memcpy(s, &st, sizeof(st));
65 return result;
66 }
67