1 /*
2  * Copyright (C) 2018 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/traced/probes/ftrace/test/cpu_reader_support.h"
18 
19 #include "perfetto/ext/base/utils.h"
20 #include "src/base/test/utils.h"
21 #include "src/traced/probes/ftrace/ftrace_procfs.h"
22 
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 
28 namespace perfetto {
29 namespace {
30 
31 std::map<std::string, std::unique_ptr<ProtoTranslationTable>>* g_tables;
32 
33 }  // namespace
34 
GetTable(const std::string & name)35 ProtoTranslationTable* GetTable(const std::string& name) {
36   if (!g_tables)
37     g_tables =
38         new std::map<std::string, std::unique_ptr<ProtoTranslationTable>>();
39   if (!g_tables->count(name)) {
40     std::string path = "src/traced/probes/ftrace/test/data/" + name + "/";
41     struct stat st;
42     if (lstat(path.c_str(), &st) == -1 && errno == ENOENT) {
43       // For OSS fuzz, which does not run in the correct cwd.
44       path = base::GetTestDataPath(path);
45     }
46     FtraceProcfs ftrace(path);
47     auto table = ProtoTranslationTable::Create(&ftrace, GetStaticEventInfo(),
48                                                GetStaticCommonFieldsInfo());
49     if (!table)
50       return nullptr;
51     g_tables->emplace(name, std::move(table));
52   }
53   return g_tables->at(name).get();
54 }
55 
PageFromXxd(const std::string & text)56 std::unique_ptr<uint8_t[]> PageFromXxd(const std::string& text) {
57   auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[base::kPageSize]);
58   const char* ptr = text.data();
59   memset(buffer.get(), 0xfa, base::kPageSize);
60   uint8_t* out = buffer.get();
61   while (*ptr != '\0') {
62     if (*(ptr++) != ':')
63       continue;
64     for (int i = 0; i < 8; i++) {
65       PERFETTO_CHECK(text.size() >=
66                      static_cast<size_t>((ptr - text.data()) + 5));
67       PERFETTO_CHECK(*(ptr++) == ' ');
68       int n = sscanf(ptr, "%02hhx%02hhx", out, out + 1);
69       PERFETTO_CHECK(n == 2);
70       out += n;
71       ptr += 4;
72     }
73     while (*ptr != '\n')
74       ptr++;
75   }
76   return buffer;
77 }
78 
79 }  // namespace perfetto
80