1 /*
2  * Copyright (C) 2020 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 "src/profiling/symbolizer/filesystem.h"
18 
19 #include "perfetto/base/build_config.h"
20 
21 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
22 #if PERFETTO_BUILDFLAG(PERFETTO_LOCAL_SYMBOLIZER)
23 #include <fts.h>
24 #include <sys/stat.h>
25 #endif
26 
27 #include <string>
28 
29 #include "perfetto/ext/base/file_utils.h"
30 
31 namespace perfetto {
32 namespace profiling {
33 #if PERFETTO_BUILDFLAG(PERFETTO_LOCAL_SYMBOLIZER)
WalkDirectories(std::vector<std::string> dirs,FileCallback fn)34 bool WalkDirectories(std::vector<std::string> dirs, FileCallback fn) {
35   std::vector<char*> dir_cstrs;
36   dir_cstrs.reserve(dirs.size());
37   for (std::string& dir : dirs)
38     dir_cstrs.emplace_back(&dir[0]);
39   dir_cstrs.push_back(nullptr);
40   base::ScopedResource<FTS*, fts_close, nullptr> fts(
41       fts_open(&dir_cstrs[0], FTS_LOGICAL | FTS_NOCHDIR, nullptr));
42   if (!fts) {
43     PERFETTO_PLOG("fts_open");
44     return false;
45   }
46   FTSENT* ent;
47   while ((ent = fts_read(*fts))) {
48     if (ent->fts_info & FTS_F)
49       fn(ent->fts_path, static_cast<size_t>(ent->fts_statp->st_size));
50   }
51   return true;
52 }
53 
GetFileSize(const std::string & file_path)54 size_t GetFileSize(const std::string& file_path) {
55   base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));
56   if (!fd) {
57     PERFETTO_PLOG("Failed to get file size %s", file_path.c_str());
58     return 0;
59   }
60   struct stat buf;
61   if (fstat(*fd, &buf) == -1) {
62     return 0;
63   }
64   return static_cast<size_t>(buf.st_size);
65 }
66 #else
67 bool WalkDirectories(std::vector<std::string>, FileCallback) {
68   return false;
69 }
70 size_t GetFileSize(const std::string&) {
71   return 0;
72 }
73 #endif
74 
75 }  // namespace profiling
76 }  // namespace perfetto
77 
78 #endif  // !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
79