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 "perfetto/base/metatrace.h"
18
19 #include <fcntl.h>
20 #include <stdlib.h>
21
22 #include "perfetto/base/build_config.h"
23 #include "perfetto/base/file_utils.h"
24 #include "perfetto/base/time.h"
25
26 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
27 #include <corecrt_io.h>
28 #endif
29
30 namespace perfetto {
31 namespace base {
32
33 namespace {
MaybeOpenTraceFile()34 int MaybeOpenTraceFile() {
35 static const char* tracing_path = getenv("PERFETTO_METATRACE_FILE");
36 if (tracing_path == nullptr)
37 return -1;
38 static int fd = open(tracing_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
39 return fd;
40 }
41 } // namespace
42
43 constexpr uint32_t MetaTrace::kMainThreadCpu;
44
WriteEvent(char type,const char * evt_name,size_t cpu)45 void MetaTrace::WriteEvent(char type, const char* evt_name, size_t cpu) {
46 int fd = MaybeOpenTraceFile();
47 if (fd == -1)
48 return;
49
50 // The JSON event format expects both "pid" and "tid" fields to create
51 // per-process tracks. Here what we really want to achieve is having one track
52 // per cpu. So we just pretend that each CPU is its own process with
53 // pid == tid == cpu.
54 char json[256];
55 int len = sprintf(json,
56 "{\"ts\": %f, \"cat\": \"PERF\", \"ph\": \"%c\", \"name\": "
57 "\"%s\", \"pid\": %zu, \"tid\": %zu},\n",
58 GetWallTimeNs().count() / 1000.0, type, evt_name, cpu, cpu);
59 ignore_result(WriteAll(fd, json, static_cast<size_t>(len)));
60 }
61
62 } // namespace base
63 } // namespace perfetto
64