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/traced/probes/ftrace/printk_formats_parser.h"
18 
19 #include <inttypes.h>
20 #include <stdio.h>
21 
22 #include "perfetto/base/logging.h"
23 #include "perfetto/ext/base/file_utils.h"
24 #include "perfetto/ext/base/optional.h"
25 #include "perfetto/ext/base/string_splitter.h"
26 #include "perfetto/ext/base/string_utils.h"
27 
28 namespace perfetto {
29 
ParsePrintkFormats(const std::string & format)30 PrintkMap ParsePrintkFormats(const std::string& format) {
31   PrintkMap mapping;
32   for (base::StringSplitter lines(format, '\n'); lines.Next();) {
33     // Lines have the format:
34     // 0xdeadbeef : "not alive cow"
35     // and may be duplicated.
36     std::string line(lines.cur_token());
37 
38     auto index = line.find(':');
39     if (index == std::string::npos)
40       continue;
41     std::string raw_address = line.substr(0, index);
42     std::string name = line.substr(index);
43 
44     // Remove colon, space and surrounding quotes:
45     raw_address = base::StripSuffix(raw_address, " ");
46     name = base::StripPrefix(name, ":");
47     name = base::StripPrefix(name, " ");
48     name = base::StripPrefix(name, "\"");
49     name = base::StripSuffix(name, "\"");
50 
51     if (name.empty())
52       continue;
53 
54     base::Optional<uint64_t> address = base::StringToUInt64(raw_address, 16);
55     if (address && address.value() != 0)
56       mapping.insert(address.value(), name);
57   }
58   return mapping;
59 }
60 
61 }  // namespace perfetto
62