cmd_list.cpp revision d115b2f738f2cef352877b26c2d93460ac9fea25
1/*
2 * Copyright (C) 2015 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 <stdio.h>
18#include <map>
19#include <string>
20#include <vector>
21
22#include <base/logging.h>
23
24#include "command.h"
25#include "event_type.h"
26#include "perf_event.h"
27
28static void PrintEventTypesOfType(uint32_t type, const std::string& type_name,
29                                  const std::vector<EventType>& event_types) {
30  printf("List of %s:\n", type_name.c_str());
31  for (auto& event_type : event_types) {
32    if (event_type.type == type && event_type.IsSupportedByKernel()) {
33      printf("  %s\n", event_type.name.c_str());
34    }
35  }
36  printf("\n");
37}
38
39class ListCommand : public Command {
40 public:
41  ListCommand()
42      : Command("list", "list available event types",
43                "Usage: simpleperf list [hw|sw|cache|tracepoint]\n"
44                "    List all available perf events on this machine.\n") {
45  }
46
47  bool Run(const std::vector<std::string>& args) override;
48};
49
50bool ListCommand::Run(const std::vector<std::string>& args) {
51  static std::map<std::string, std::pair<int, std::string>> type_map = {
52      {"hw", {PERF_TYPE_HARDWARE, "hardware events"}},
53      {"sw", {PERF_TYPE_SOFTWARE, "software events"}},
54      {"cache", {PERF_TYPE_HW_CACHE, "hw-cache events"}},
55      {"tracepoint", {PERF_TYPE_TRACEPOINT, "tracepoint events"}},
56  };
57
58  std::vector<std::string> names;
59  if (args.empty()) {
60    for (auto& item : type_map) {
61      names.push_back(item.first);
62    }
63  } else {
64    for (auto& arg : args) {
65      if (type_map.find(arg) != type_map.end()) {
66        names.push_back(arg);
67      } else {
68        LOG(ERROR) << "unknown event type category: " << arg << ", try using \"help list\"";
69        return false;
70      }
71    }
72  }
73
74  auto& event_types = GetAllEventTypes();
75
76  for (auto& name : names) {
77    auto it = type_map.find(name);
78    PrintEventTypesOfType(it->second.first, it->second.second, event_types);
79  }
80  return true;
81}
82
83__attribute__((constructor)) static void RegisterListCommand() {
84  RegisterCommand("list", [] { return std::unique_ptr<Command>(new ListCommand); });
85}
86